"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Plus, ListChecks, Pencil, Trash2, Check, LayoutGrid } from "lucide-react"
import { cn } from "@/lib/utils"
import { toast } from "sonner"
import { Badge } from "@/components/ui/badge"

export interface ModuleSelectProps {
  value: string[]
  onValueChange: (value: string[]) => void
  label?: React.ReactNode
  required?: boolean
  disabled?: boolean
}

const DEFAULT_MODULES = [
  "Leads",
  "Sales",
  "Contacts",
  "Customers",
  "Tasks",
  "Brands",
  "Divisions",
  "Services",
]

export function ModuleSelect({
  value,
  onValueChange,
  label,
  required,
  disabled = false,
}: ModuleSelectProps) {
  const [customModules, setCustomModules] = React.useState<string[]>([])
  const [addModuleOpen, setAddModuleOpen] = React.useState(false)
  const [manageModulesOpen, setManageModulesOpen] = React.useState(false)
  const [newModuleName, setNewModuleName] = React.useState("")
  const [editingModuleIdx, setEditingModuleIdx] = React.useState<number | null>(null)
  const [editingModuleName, setEditingModuleName] = React.useState("")

  // Load custom modules from localStorage on mount
  React.useEffect(() => {
    const saved = localStorage.getItem("crm_custom_modules")
    if (saved) {
      try {
        setCustomModules(JSON.parse(saved))
      } catch (e) {
        console.error("Failed to load custom modules", e)
      }
    }
  }, [])

  // Save custom modules to localStorage when changed
  const saveCustomModules = (modules: string[]) => {
    setCustomModules(modules)
    localStorage.setItem("crm_custom_modules", JSON.stringify(modules))
  }

  const allOptions = React.useMemo(() => {
    return Array.from(new Set([...DEFAULT_MODULES, ...customModules]))
  }, [customModules])

  const handleToggle = (mod: string) => {
    const next = value.includes(mod)
      ? value.filter((v) => v !== mod)
      : [...value, mod]
    onValueChange(next)
  }

  const handleAddModule = () => {
    const name = newModuleName.trim()
    if (!name) return
    if (allOptions.includes(name)) {
        toast.error("Module already exists")
        return
    }
    const next = [...customModules, name]
    saveCustomModules(next)
    onValueChange([...value, name])
    setNewModuleName("")
    setAddModuleOpen(false)
    toast.success(`Module "${name}" added`)
  }

  const handleUpdateModule = () => {
    if (editingModuleIdx === null || !editingModuleName.trim()) return
    const oldName = customModules[editingModuleIdx]
    const newName = editingModuleName.trim()
    
    const next = [...customModules]
    next[editingModuleIdx] = newName
    saveCustomModules(next)

    // Update selection if old name was selected
    if (value.includes(oldName)) {
      onValueChange(value.map(v => v === oldName ? newName : v))
    }

    setEditingModuleIdx(null)
    setEditingModuleName("")
  }

  const handleDeleteModule = (mod: string) => {
    if (!confirm(`Remove custom module "${mod}"?`)) return
    const next = customModules.filter(m => m !== mod)
    saveCustomModules(next)
    if (value.includes(mod)) {
      onValueChange(value.filter(v => v !== mod))
    }
    toast.success("Module removed")
  }

  return (
    <div className="space-y-2">
      {label != null && (
        <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none ml-1">
          {label}
          {required && <span className="text-red-500 ml-0.5">*</span>}
        </label>
      )}
      
      <div className="flex items-center gap-2">
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              className={cn(
                "h-auto min-h-[44px] flex-1 flex flex-wrap gap-2 p-2 bg-gray-50/50 border-gray-200 rounded-xl justify-start hover:bg-gray-100/50 transition-all",
                disabled && "opacity-50 pointer-events-none"
              )}
            >
              {value.length === 0 ? (
                <span className="text-[13px] text-gray-400 font-medium px-2">Select modules...</span>
              ) : (
                <div className="flex flex-wrap gap-1.5">
                  {value.map((mod) => (
                    <Badge
                      key={mod}
                      variant="secondary"
                      className="bg-accent/10 text-accent border-accent/20 px-2 py-0.5 rounded-lg text-[11px] font-bold"
                    >
                      {mod}
                    </Badge>
                  ))}
                </div>
              )}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-[300px] p-2 rounded-2xl shadow-premium border-border/40" align="start">
             <div className="p-2 border-b border-border/40 mb-2">
                <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest px-1">Available Modules</p>
             </div>
             <div className="max-h-[240px] overflow-y-auto space-y-0.5 p-1 scrollbar-themed">
                {allOptions.map((mod) => {
                    const isSelected = value.includes(mod);
                    return (
                        <button
                            key={mod}
                            onClick={() => handleToggle(mod)}
                            className={cn(
                                "flex items-center justify-between w-full p-2.5 rounded-xl text-[13px] font-semibold transition-all group",
                                isSelected 
                                    ? "bg-accent/5 text-accent" 
                                    : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
                            )}
                        >
                            <span>{mod}</span>
                            {isSelected && <Check size={14} className="text-accent" />}
                        </button>
                    )
                })}
             </div>
          </PopoverContent>
        </Popover>

        <Popover open={addModuleOpen} onOpenChange={setAddModuleOpen}>
          <PopoverTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="h-11 w-11 shrink-0 rounded-xl border-gray-200 bg-gray-50 hover:bg-gray-100 hover:border-accent/40 hover:text-accent transition-all shadow-sm"
              disabled={disabled}
            >
              <Plus size={18} />
            </Button>
          </PopoverTrigger>
          <PopoverContent align="end" className="w-64 p-3 rounded-2xl shadow-premium border-border/40">
            <p className="text-[12px] font-bold text-gray-700 mb-2.5 px-1 font-['Lexend']">
              Add New Module
            </p>
            <div className="space-y-3">
                <Input
                value={newModuleName}
                onChange={(e) => setNewModuleName(e.target.value)}
                placeholder="e.g. Inventory"
                className="h-10 text-[13px] rounded-xl border-gray-200"
                onKeyDown={(e) =>
                    e.key === "Enter" && (e.preventDefault(), handleAddModule())
                }
                />
                <Button
                type="button"
                className="w-full bg-accent rounded-xl h-10 font-bold"
                disabled={!newModuleName.trim()}
                onClick={handleAddModule}
                >
                Add Module
                </Button>
            </div>
          </PopoverContent>
        </Popover>

        <Popover open={manageModulesOpen} onOpenChange={setManageModulesOpen}>
          <PopoverTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="h-11 w-11 shrink-0 rounded-xl border-gray-200 bg-gray-50 hover:bg-gray-100 hover:border-accent/40 hover:text-accent transition-all shadow-sm"
              disabled={disabled}
            >
              <ListChecks size={18} />
            </Button>
          </PopoverTrigger>
          <PopoverContent align="end" className="w-72 p-2 rounded-2xl shadow-premium border-border/40">
            <p className="text-[12px] font-bold text-gray-700 px-2.5 py-2 font-['Lexend']">
              Manage Custom Modules
            </p>
            <div className="max-h-56 overflow-y-auto space-y-1 p-1 scrollbar-themed">
              {customModules.length === 0 && (
                <div className="flex flex-col items-center justify-center py-6 px-4 text-center">
                    <LayoutGrid size={24} className="text-gray-200 mb-2" />
                    <p className="text-[11px] text-gray-400 font-medium">
                        Only custom added modules can be edited or removed from the list.
                    </p>
                </div>
              )}
              {customModules.map((mod, idx) => (
                <div
                  key={mod}
                  className="flex items-center gap-2 rounded-xl border border-transparent hover:bg-gray-50 px-2 py-1.5 group"
                >
                  {editingModuleIdx === idx ? (
                    <div className="flex items-center gap-1.5 w-full">
                      <Input
                        value={editingModuleName}
                        onChange={(e) => setEditingModuleName(e.target.value)}
                        className="h-8 text-[12px] flex-1 rounded-lg"
                        autoFocus
                        onKeyDown={(e) => {
                          if (e.key === "Enter") handleUpdateModule()
                          if (e.key === "Escape") setEditingModuleIdx(null)
                        }}
                      />
                      <Button
                        type="button"
                        size="sm"
                        className="h-7 px-2 bg-accent text-[11px]"
                        onClick={handleUpdateModule}
                      >
                        Save
                      </Button>
                    </div>
                  ) : (
                    <>
                      <span className="text-[13px] font-medium flex-1 truncate text-gray-700 pl-1">
                        {mod}
                      </span>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"
                        onClick={() => {
                          setEditingModuleIdx(idx)
                          setEditingModuleName(mod)
                        }}
                      >
                        <Pencil size={12} className="text-gray-400" />
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity text-red-500 hover:text-red-600 hover:bg-red-50"
                        onClick={() => handleDeleteModule(mod)}
                      >
                        <Trash2 size={12} />
                      </Button>
                    </>
                  )}
                </div>
              ))}
            </div>
          </PopoverContent>
        </Popover>
      </div>
    </div>
  )
}
