"use client";

import React, { useState, useRef, useEffect } from "react";
import type { WarehouseRecord } from "@/lib/api";

/**
 * WarehouseMultiSelect Component
 *
 * A multi-select dropdown for choosing warehouses in the Stock Movement Sheet modal.
 * Features checkbox-based selection with visual indicators, "Select All" and "Clear All" functionality.
 *
 * Design matches the premium patterns from WarehouseEntryModal.
 */

// Brand colors matching WarehouseEntryModal
const BRAND = "#4c6fff";
const BRAND_GRADIENT = "linear-gradient(135deg, #4c6fff 0%, #5b7cff 100%)";

interface WarehouseMultiSelectProps {
  warehouses: WarehouseRecord[];
  selected: string[];  // Warehouse IDs
  onChange: (selected: string[]) => void;
}

export default function WarehouseMultiSelect({
  warehouses,
  selected,
  onChange,
}: WarehouseMultiSelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });
  const dropdownRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen]);

  // Update dropdown position when it opens
  useEffect(() => {
    if (isOpen && buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      setDropdownPosition({
        top: rect.bottom + window.scrollY + 6,
        left: rect.left + window.scrollX,
        width: rect.width,
      });
    }
  }, [isOpen]);

  function toggleWarehouse(warehouseId: string) {
    if (selected.includes(warehouseId)) {
      onChange(selected.filter(id => id !== warehouseId));
    } else {
      onChange([...selected, warehouseId]);
    }
  }

  function selectAll() {
    // Select all filtered warehouses
    const filteredIds = filteredWarehouses.map(w => w._id);
    const newSelected = [...new Set([...selected, ...filteredIds])];
    onChange(newSelected);
  }

  function clearAll() {
    // Clear all filtered warehouses
    const filteredIds = new Set(filteredWarehouses.map(w => w._id));
    const newSelected = selected.filter(id => !filteredIds.has(id));
    onChange(newSelected);
  }

  // Filter warehouses based on search query
  const filteredWarehouses = warehouses.filter(w =>
    w.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Sort: selected warehouses first (even if filtered out), then filtered unselected
  const selectedWarehouses = warehouses.filter(w => selected.includes(w._id));
  const unselectedFilteredWarehouses = filteredWarehouses.filter(w => !selected.includes(w._id));
  const displayWarehouses = [...selectedWarehouses, ...unselectedFilteredWarehouses];

  const selectedCount = selected.length;
  const allFilteredSelected = filteredWarehouses.length > 0 && 
    filteredWarehouses.every(w => selected.includes(w._id));

  return (
    <div ref={dropdownRef} style={{ position: "relative", width: "100%" }}>
      {/* Dropdown Button */}
      <button
        ref={buttonRef}
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        style={{
          width: "100%",
          padding: "11px 16px",
          borderRadius: 8,
          border: isOpen ? `2px solid ${BRAND}` : "1.5px solid rgba(0,0,0,0.12)",
          background: "#fff",
          fontSize: "0.88rem",
          fontWeight: 600,
          color: selectedCount > 0 ? "#1a202c" : "#868e96",
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 10,
          outline: "none",
          transition: "border-color 0.15s ease",
          boxSizing: "border-box",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {/* Warehouse icon */}
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke={selectedCount > 0 ? BRAND : "#868e96"}
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
            <polyline points="9 22 9 12 15 12 15 22" />
          </svg>
          <span>
            {selectedCount === 0
              ? "Select Warehouses"
              : selectedCount === warehouses.length
              ? `All Warehouses (${selectedCount})`
              : `${selectedCount} Warehouse${selectedCount !== 1 ? "s" : ""} Selected`}
          </span>
        </div>

        {/* Dropdown arrow */}
        <svg
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          style={{
            transform: isOpen ? "rotate(180deg)" : "rotate(0deg)",
            transition: "transform 0.2s ease",
          }}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {/* Dropdown Panel */}
      {isOpen && (
        <div
          ref={dropdownRef}
          style={{
            position: "fixed",
            top: dropdownPosition.top,
            left: dropdownPosition.left,
            width: dropdownPosition.width,
            zIndex: 999999,
            background: "#fff",
            borderRadius: 10,
            border: "1.5px solid rgba(76, 111, 255, 0.25)",
            boxShadow: "0 12px 32px rgba(15,22,48,0.18), 0 0 0 1px rgba(76,111,255,0.08)",
            maxHeight: 320,
            display: "flex",
            flexDirection: "column",
            overflow: "hidden",
          }}
        >
          {/* Header with Select All / Clear All */}
          <div
            style={{
              padding: "12px 16px",
              borderBottom: "1px solid rgba(0,0,0,0.07)",
              background: "#f8f9fb",
              display: "flex",
              gap: 8,
            }}
          >
            <button
              type="button"
              onClick={selectAll}
              disabled={allFilteredSelected || filteredWarehouses.length === 0}
              style={{
                flex: 1,
                padding: "7px 12px",
                borderRadius: 6,
                border: "none",
                background: (allFilteredSelected || filteredWarehouses.length === 0) ? "rgba(76,111,255,0.1)" : BRAND_GRADIENT,
                color: (allFilteredSelected || filteredWarehouses.length === 0) ? "rgba(76,111,255,0.5)" : "#fff",
                fontSize: "0.8rem",
                fontWeight: 600,
                cursor: (allFilteredSelected || filteredWarehouses.length === 0) ? "not-allowed" : "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6,
              }}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12" />
              </svg>
              Select All
            </button>
            <button
              type="button"
              onClick={clearAll}
              disabled={selectedCount === 0}
              style={{
                flex: 1,
                padding: "7px 12px",
                borderRadius: 6,
                border: "1.5px solid rgba(0,0,0,0.12)",
                background: "#fff",
                color: selectedCount === 0 ? "#adb5bd" : "#495057",
                fontSize: "0.8rem",
                fontWeight: 600,
                cursor: selectedCount === 0 ? "not-allowed" : "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6,
              }}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
              Clear All
            </button>
          </div>

          {/* Search Input */}
          <div
            style={{
              padding: "12px 16px",
              borderBottom: "1px solid rgba(0,0,0,0.07)",
              background: "#fff",
            }}
          >
            <div style={{ position: "relative" }}>
              {/* Search Icon */}
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#868e96"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{
                  position: "absolute",
                  left: 12,
                  top: "50%",
                  transform: "translateY(-50%)",
                  pointerEvents: "none",
                }}
              >
                <circle cx="11" cy="11" r="8" />
                <path d="m21 21-4.35-4.35" />
              </svg>

              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search warehouses..."
                style={{
                  width: "100%",
                  padding: "9px 36px 9px 38px",
                  borderRadius: 7,
                  border: "1.5px solid rgba(0,0,0,0.12)",
                  fontSize: "0.85rem",
                  outline: "none",
                  transition: "border-color 0.15s ease",
                  boxSizing: "border-box",
                }}
                onFocus={(e) => {
                  e.currentTarget.style.borderColor = BRAND;
                }}
                onBlur={(e) => {
                  e.currentTarget.style.borderColor = "rgba(0,0,0,0.12)";
                }}
              />

              {/* Clear Search Button */}
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => setSearchQuery("")}
                  style={{
                    position: "absolute",
                    right: 8,
                    top: "50%",
                    transform: "translateY(-50%)",
                    width: 24,
                    height: 24,
                    borderRadius: "50%",
                    border: "none",
                    background: "rgba(0,0,0,0.08)",
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    padding: 0,
                    transition: "background 0.15s ease",
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.background = "rgba(0,0,0,0.15)";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.background = "rgba(0,0,0,0.08)";
                  }}
                >
                  <svg
                    width="12"
                    height="12"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#495057"
                    strokeWidth="2.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </svg>
                </button>
              )}
            </div>
          </div>

          {/* Warehouse List */}
          <div
            style={{
              overflowY: "auto",
              flex: 1,
              padding: "8px",
            }}
          >
            {displayWarehouses.length === 0 ? (
              <div
                style={{
                  padding: "24px 16px",
                  textAlign: "center",
                  color: "#868e96",
                  fontSize: "0.85rem",
                }}
              >
                No warehouses found
              </div>
            ) : (
              displayWarehouses.map((warehouse) => {
                const isSelected = selected.includes(warehouse._id);
                const isFilteredOut = searchQuery && !warehouse.name.toLowerCase().includes(searchQuery.toLowerCase());
                
                return (
                  <label
                    key={warehouse._id}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "10px 12px",
                      borderRadius: 8,
                      background: isSelected ? "rgba(76,111,255,0.06)" : "transparent",
                      cursor: "pointer",
                      transition: "background 0.15s ease",
                      marginBottom: 4,
                      opacity: isFilteredOut ? 0.5 : 1,
                    }}
                    onMouseEnter={(e) => {
                      if (!isSelected) {
                        e.currentTarget.style.background = "#f8f9fb";
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!isSelected) {
                        e.currentTarget.style.background = "transparent";
                      }
                    }}
                  >
                    {/* Custom Checkbox */}
                    <div
                      style={{
                        width: 20,
                        height: 20,
                        borderRadius: 5,
                        border: isSelected ? `2px solid ${BRAND}` : "2px solid rgba(0,0,0,0.2)",
                        background: isSelected ? BRAND : "#fff",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        flexShrink: 0,
                        transition: "all 0.15s ease",
                      }}
                    >
                      {isSelected && (
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      )}
                    </div>

                    {/* Hidden native checkbox for accessibility */}
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={() => toggleWarehouse(warehouse._id)}
                      style={{
                        position: "absolute",
                        opacity: 0,
                        pointerEvents: "none",
                      }}
                    />

                    {/* Warehouse Icon */}
                    <div
                      style={{
                        width: 32,
                        height: 32,
                        borderRadius: 7,
                        background: isSelected ? BRAND_GRADIENT : "#e9ecef",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        flexShrink: 0,
                      }}
                    >
                      <svg
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke={isSelected ? "#fff" : "#868e96"}
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
                        <polyline points="9 22 9 12 15 12 15 22" />
                      </svg>
                    </div>

                    {/* Warehouse Name */}
                    <span
                      style={{
                        fontSize: "0.88rem",
                        fontWeight: 600,
                        color: isSelected ? BRAND : "#495057",
                        flex: 1,
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                      }}
                    >
                      {warehouse.name}
                    </span>
                  </label>
                );
              })
            )}
          </div>
        </div>
      )}
    </div>
  );
}
