"use client"

import * as React from "react"
import { Tag, Plus, Pencil, Trash2, RefreshCw, Info } from "lucide-react"
import { 
  useGetBrandsQuery, 
  useCreateBrandMutation, 
  useUpdateBrandMutation, 
  useDeleteBrandMutation,
  type Brand 
} from "@/api/rtk/brands-api"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog"
import { DeleteDialog } from "@/components/ui/delete-dialog"
import { toast } from "sonner"

export function BrandsTab() {
  const { data: brands = [], isLoading, isFetching } = useGetBrandsQuery()
  const [createBrand, { isLoading: creating }] = useCreateBrandMutation()
  const [updateBrand, { isLoading: updating }] = useUpdateBrandMutation()
  const [deleteBrand, { isLoading: deleting }] = useDeleteBrandMutation()

  const [isFormOpen, setIsFormOpen] = React.useState(false)
  const [formMode, setFormMode] = React.useState<"create" | "edit">("create")
  const [formState, setFormState] = React.useState({ id: "", name: "" })

  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
  const [brandToDelete, setBrandToDelete] = React.useState<Brand | null>(null)

  const openCreate = () => {
    setFormMode("create")
    setFormState({ id: "", name: "" })
    setIsFormOpen(true)
  }

  const openEdit = (brand: Brand) => {
    setFormMode("edit")
    setFormState({ id: brand.id, name: brand.name })
    setIsFormOpen(true)
  }

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const name = formState.name.trim()
    if (!name) {
      toast.error("Brand name is required")
      return
    }

    try {
      if (formMode === "create") {
        await createBrand({ name }).unwrap()
        toast.success("Brand created")
      } else {
        await updateBrand({ id: formState.id, name }).unwrap()
        toast.success("Brand updated")
      }
      setIsFormOpen(false)
    } catch (error: any) {
      toast.error(error?.data?.message || "Failed to save brand")
    }
  }

  const confirmDelete = (brand: Brand) => {
    setBrandToDelete(brand)
    setDeleteDialogOpen(true)
  }

  const handleDelete = async () => {
    if (!brandToDelete) return
    try {
      await deleteBrand(brandToDelete.id).unwrap()
      toast.success("Brand deleted")
      setDeleteDialogOpen(false)
    } catch (error: any) {
      toast.error(error?.data?.message || "Failed to delete brand")
    }
  }

  return (
    <div className="space-y-5 animate-in fade-in duration-500">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 border-b border-white/20 pb-4">
        <div className="flex items-center gap-3">
          <div className="h-9 w-9 rounded-xl bg-[#6C63FF]/10 flex items-center justify-center text-[#6C63FF]">
            <Tag size={18} />
          </div>
          <div>
            <h2 className="text-[18px] font-extrabold text-gray-900 font-['Lexend'] tracking-tight">
              Brands
            </h2>
            <p className="text-[12px] text-gray-400 mt-0.5">
              Manage product brands and labels.
            </p>
          </div>
        </div>
        <Button size="sm" onClick={openCreate} className="gap-2 rounded-xl">
          <Plus size={14} />
          Add Brand
        </Button>
      </div>

      <div className="rounded-2xl border border-white/40 bg-white/50 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] overflow-hidden">
        <div className="px-4 py-3 border-b border-white/40 flex items-center justify-between gap-3 bg-white/30">
          <div className="flex items-center gap-2 text-[12px] text-gray-500 font-medium">
            <Info size={14} className="text-gray-400" />
            <span>Brands are used to categorize deals and products.</span>
          </div>
          {(isLoading || isFetching) && (
            <div className="flex items-center gap-2 text-[11px] text-[#6C63FF]">
              <RefreshCw size={12} className="animate-spin" />
              <span>Updating...</span>
            </div>
          )}
        </div>

        <div className="overflow-x-auto">
          <Table>
            <TableHeader className="bg-gray-50/50">
              <TableRow className="border-b border-white/40 hover:bg-transparent">
                <TableHead className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">Name</TableHead>
                <TableHead className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">Created</TableHead>
                <TableHead className="text-right text-[11px] font-bold text-gray-400 uppercase tracking-wider">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {brands.length === 0 && !isLoading ? (
                <TableRow>
                  <TableCell colSpan={3} className="h-32 text-center text-gray-400 text-[13px]">
                    No brands found. Click "Add Brand" to create one.
                  </TableCell>
                </TableRow>
              ) : (
                brands.map((brand) => (
                  <TableRow key={brand.id} className="border-b border-white/40 hover:bg-white/40 transition-colors">
                    <TableCell className="py-4">
                      <span className="text-[14px] font-semibold text-gray-900">{brand.name}</span>
                    </TableCell>
                    <TableCell className="py-4">
                      <span className="text-[12px] text-gray-500">
                        {brand.createdAt ? new Date(brand.createdAt).toLocaleDateString() : "—"}
                      </span>
                    </TableCell>
                    <TableCell className="py-4 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-gray-400 hover:text-[#6C63FF] hover:bg-[#6C63FF]/5 rounded-lg"
                          onClick={() => openEdit(brand)}
                        >
                          <Pencil size={14} />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg"
                          onClick={() => confirmDelete(brand)}
                        >
                          <Trash2 size={14} />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
        <DialogContent className="sm:max-w-[400px] rounded-3xl border-white/40 bg-white/90 backdrop-blur-xl">
          <DialogHeader>
            <DialogTitle className="text-[18px] font-extrabold text-gray-900 font-['Lexend']">
              {formMode === "create" ? "Add New Brand" : "Edit Brand"}
            </DialogTitle>
            <DialogDescription className="text-[13px] text-gray-500">
              {formMode === "create" ? "Enter a unique name for the new brand." : "Update the brand name below."}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleFormSubmit} className="space-y-4 py-2">
            <div className="space-y-2">
              <Label htmlFor="brand-name" className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">Brand Name</Label>
              <Input
                id="brand-name"
                value={formState.name}
                onChange={(e) => setFormState(prev => ({ ...prev, name: e.target.value }))}
                placeholder="e.g. Acme Corp"
                className="h-11 rounded-xl border-gray-200 bg-white/50 focus:bg-white"
                autoFocus
              />
            </div>
            <DialogFooter className="pt-2">
              <Button type="button" variant="ghost" onClick={() => setIsFormOpen(false)} className="rounded-xl">
                Cancel
              </Button>
              <Button type="submit" disabled={creating || updating || !formState.name.trim()} className="rounded-xl px-6">
                {(creating || updating) ? (
                  <RefreshCw size={14} className="animate-spin mr-2" />
                ) : null}
                Save Brand
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <DeleteDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={handleDelete}
        title="Delete Brand"
        description={`Are you sure you want to delete "${brandToDelete?.name}"? This action cannot be undone.`}
        isLoading={deleting}
      />
    </div>
  )
}
