"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { ReactSelect } from "@/components/ui/react-select"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Plus, ListChecks, Pencil, Trash2 } from "lucide-react"
import { cn } from "@/lib/utils"
import { toast } from "sonner"
import {
  useGetAccountTiersQuery,
  useCreateAccountTierMutation,
  useUpdateAccountTierMutation,
  useDeleteAccountTierMutation,
} from "@/api/rtk/account-tiers-api"

export interface AccountTierSelectProps {
  value: string
  onValueChange: (value: string) => void
  label?: React.ReactNode
  placeholder?: string
  allowEmpty?: boolean
  disabled?: boolean
  skip?: boolean
  triggerClassName?: string
}

export function AccountTierSelect({
  value,
  onValueChange,
  label,
  placeholder = "Select account tier",
  allowEmpty = false,
  disabled = false,
  skip = false,
  triggerClassName,
}: AccountTierSelectProps) {
  const { data: tiers = [] } = useGetAccountTiersQuery(undefined, { skip })
  const [createTier, { isLoading: creating }] = useCreateAccountTierMutation()
  const [updateTier, { isLoading: updating }] = useUpdateAccountTierMutation()
  const [deleteTier] = useDeleteAccountTierMutation()
  const [addOpen, setAddOpen] = React.useState(false)
  const [manageOpen, setManageOpen] = React.useState(false)
  const [newName, setNewName] = React.useState("")
  const [editingId, setEditingId] = React.useState<string | null>(null)
  const [editingName, setEditingName] = React.useState("")

  const displayList = React.useMemo(() => {
    const names = new Set(tiers.map((t) => t.name))
    if (value.trim() && !names.has(value)) {
      return [...tiers, { id: "__current__", name: value }]
    }
    return tiers
  }, [tiers, value])

  const tierOptions = React.useMemo(
    () => displayList.map((t) => ({ value: t.name, label: t.name })),
    [displayList],
  )

  const handleAdd = async () => {
    const name = newName.trim()
    if (!name) return
    try {
      const result = await createTier({ name }).unwrap()
      onValueChange(result.name)
      setNewName("")
      setAddOpen(false)
      toast.success("Account tier added")
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to add account tier")
    }
  }

  const handleUpdate = async () => {
    if (!editingId || editingId === "__current__" || !editingName.trim()) return
    try {
      const result = await updateTier({
        id: editingId,
        name: editingName.trim(),
      }).unwrap()
      const oldName = tiers.find((t) => t.id === editingId)?.name
      if (value === oldName) onValueChange(result.name)
      setEditingId(null)
      setEditingName("")
      setManageOpen(false)
      toast.success("Account tier updated")
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to update account tier")
    }
  }

  const handleDelete = async (id: string, name: string) => {
    if (id === "__current__") return
    if (!confirm(`Delete account tier "${name}"?`)) return
    try {
      await deleteTier(id).unwrap()
      if (value === name) onValueChange("")
      toast.success("Account tier deleted")
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to delete account tier")
    }
  }

  return (
    <div>
      {label != null && (
        <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
          {label}
        </label>
      )}
      <div className="flex items-center gap-2">
        <ReactSelect
          value={value}
          onValueChange={onValueChange}
          options={tierOptions}
          placeholder={placeholder}
          allowEmpty={allowEmpty}
          disabled={disabled}
          triggerClassName={cn(
            "h-10 min-h-10 flex-1 bg-gray-50 border-gray-200 rounded-xl text-[14px] font-medium",
            triggerClassName,
          )}
          contentClassName="rounded-xl"
        />
        <Popover open={addOpen} onOpenChange={setAddOpen}>
          <PopoverTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="h-10 w-10 shrink-0 rounded-xl border-gray-200 bg-gray-50 hover:bg-gray-100"
              aria-label="Add new account tier"
              disabled={disabled}
            >
              <Plus size={16} />
            </Button>
          </PopoverTrigger>
          <PopoverContent align="end" className="w-64">
            <p className="text-[12px] font-semibold text-gray-700 mb-2">New account tier</p>
            <Input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="e.g. Tier 1"
              className="h-9 text-[13px] mb-2"
              onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), handleAdd())}
            />
            <Button
              type="button"
              size="sm"
              className="w-full"
              disabled={!newName.trim() || creating}
              onClick={handleAdd}
            >
              {creating ? "Adding..." : "Add"}
            </Button>
          </PopoverContent>
        </Popover>
        <Popover open={manageOpen} onOpenChange={setManageOpen}>
          <PopoverTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="h-10 w-10 shrink-0 rounded-xl border-gray-200 bg-gray-50 hover:bg-gray-100"
              aria-label="Manage account tiers"
              disabled={disabled}
            >
              <ListChecks size={16} />
            </Button>
          </PopoverTrigger>
          <PopoverContent align="end" className="w-72 p-2">
            <p className="text-[12px] font-semibold text-gray-700 px-2 py-1.5">Manage account tiers</p>
            <div className="max-h-48 overflow-y-auto space-y-1 scrollbar-themed">
              {tiers.length === 0 && (
                <p className="text-[12px] text-gray-500 px-2 py-2">No tiers yet. Use + to add.</p>
              )}
              {tiers.map((t) => (
                <div
                  key={t.id}
                  className="flex items-center gap-2 rounded-lg border border-transparent hover:bg-gray-50 px-2 py-1.5 group"
                >
                  {editingId === t.id ? (
                    <>
                      <Input
                        value={editingName}
                        onChange={(e) => setEditingName(e.target.value)}
                        className="h-8 text-[13px] flex-1"
                        autoFocus
                        onKeyDown={(e) => {
                          if (e.key === "Enter") handleUpdate()
                          if (e.key === "Escape") setEditingId(null)
                        }}
                      />
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2"
                        onClick={handleUpdate}
                        disabled={updating || !editingName.trim()}
                      >
                        Save
                      </Button>
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2"
                        onClick={() => {
                          setEditingId(null)
                          setEditingName("")
                        }}
                      >
                        Cancel
                      </Button>
                    </>
                  ) : (
                    <>
                      <span className="text-[13px] font-medium flex-1 truncate">{t.name}</span>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 shrink-0 opacity-70 hover:opacity-100"
                        aria-label="Edit account tier"
                        onClick={() => {
                          setEditingId(t.id)
                          setEditingName(t.name)
                        }}
                      >
                        <Pencil size={12} />
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 shrink-0 opacity-70 hover:opacity-100 text-red-600 hover:text-red-700"
                        aria-label="Delete account tier"
                        onClick={() => handleDelete(t.id, t.name)}
                      >
                        <Trash2 size={12} />
                      </Button>
                    </>
                  )}
                </div>
              ))}
            </div>
          </PopoverContent>
        </Popover>
      </div>
    </div>
  )
}
