"use client";

import { useState, useEffect } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Switch } from "../../../../../src/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../../src/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../../../../../src/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../src/components/ui/table";
import { Badge } from "../../../../../src/components/ui/badge";
import { Plus, Edit, Trash2, Search, ChevronLeft, ChevronRight, Eye, X, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react";
import { toast } from "sonner";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";

interface Color {
  _id: string;
  name: string;
  hexCode: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export default function ColorsManagement() {
  const [colors, setColors] = useState<Color[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAddEditDialogOpen, setIsAddEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [editingColor, setEditingColor] = useState<Color | null>(null);
  const [viewingColor, setViewingColor] = useState<Color | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortField, setSortField] = useState<"name" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  // const [sortOrder, setSortOrder] = useState<"desc" | "asc">("desc");
  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10
  });

  const [formData, setFormData] = useState({
    name: "",
    hexCode: "#000000",
    isActive: true,
  });

  const debouncedSearch = useDebounce(search, 500)

  useEffect(() => {
    fetchColors();
  }, [debouncedSearch, page, limit, sortField, sortOrder]);

  const fetchColors = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch })
      });
      
      const res = await fetch(`/api/colors?${params}`);
      const result = await res.json();
      if (result.success) {
        setColors(result.data);
        setPagination(result.pagination);
      } else {
        toast.error("Failed to fetch colors");
      }
    } catch {
      toast.error("Error fetching colors");
    } finally {
      setLoading(false);
    }
  };

  const handleLimitChange = (value: string) => {
    const newLimit = parseInt(value);
    setLimit(newLimit);
    setPage(1);
  };

  const handleSort = (field: "name" | "createdAt") => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      if (field === "name") {
        setSortOrder("asc");
      } else {
        setSortOrder("desc");
      }
    }
    setPage(1);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      const url = editingColor
        ? `/api/colors/${editingColor._id}`
        : "/api/colors";
      const method = editingColor ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      const result = await res.json();

      if (result.success) {
        toast.success(
          editingColor
            ? "Color updated successfully"
            : "Color created successfully"
        );
        setIsAddEditDialogOpen(false);
        setEditingColor(null);
        resetForm();
        fetchColors();
      } else {
        toast.error(result.error || "Failed to save color");
      }
    } catch {
      toast.error("Error saving color");
    }
  };

  const handleEdit = (color: Color) => {
    setEditingColor(color);
    setFormData({
      name: color.name,
      hexCode: color.hexCode || "#000000",
      isActive: color.isActive,
    });
    setIsAddEditDialogOpen(true);
  };

  const handleView = (color: Color) => {
    setViewingColor(color);
    setIsViewDialogOpen(true);
  };

const handleDelete = async (colorId: string) => {
  if (!confirm("Are you sure you want to delete this color?")) return;

  try {
    const res = await fetch(`/api/colors/${colorId}`, {
      method: "DELETE",
    });

    const result = await res.json();

    if (result.success) {
      toast.success("Color deleted successfully");

      // If deleting last item on current page
      if (colors.length === 1 && page > 1) {
        setPage((prev) => prev - 1);
      } else {
        fetchColors();
      }
    } else {
      toast.error(result.error || "Failed to delete color");
    }
  } catch {
    toast.error("Error deleting color");
  }
};

  const resetForm = () => {
    setFormData({
      name: "",
      hexCode: "#000000",
      isActive: true,
    });
  };

  const handleSearch = (value: string) => {
    setSearch(value);
    setPage(1);
  };
  const isValidColorName = (name: string) => {
  return /^[A-Za-z0-9\s]+$/.test(name); // letters + numbers + space
};
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="rounded-sm">
      {/* Header */}      

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-md">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-2 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader className="flex-shrink-0">
                <DialogTitle>Color Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                      setIsViewDialogOpen(false);
                    }}
                />
              </DialogHeader>
              
              {viewingColor && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
     
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                    <div className="space-y-4 pb-4">
                      <div className="flex justify-center">
                        <div className="text-center space-y-2">
                          <div
                            className="w-32 h-32 rounded-lg border-2 shadow-lg mx-auto"
                            style={{ backgroundColor: viewingColor.hexCode }}
                          />
                          <p className="text-sm font-mono font-medium">
                            {viewingColor.hexCode}
                          </p>
                        </div>
                      </div>

                      <div className="space-y-3">
                        <div className="flex items-center justify-evenly gap-12">
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">Color Name</Label>
                            <p className="text-base font-medium">{viewingColor.name}</p>
                          </div>

                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">Hex Code</Label>
                            <div className="flex items-center gap-2">
                              <div
                                className="w-5 h-5 rounded border"
                                style={{ backgroundColor: viewingColor.hexCode }}
                              />
                              <p className="text-sm font-mono">{viewingColor.hexCode}</p>
                            </div>
                          </div>

                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500 mr-2">Status</Label>
                            <Badge variant={viewingColor.isActive ? "default" : "secondary"}>
                              {viewingColor.isActive ? "Active" : "Inactive"}
                            </Badge>
                          </div>
                        </div>

                        <div className="pt-2 mt-2 border-t">
                          <div className="space-y-2">
                            <div className="space-y-0.5">
                              <Label className="text-xs text-gray-500">Created At</Label>
                              <p className="text-xs text-gray-600">{formatDate(viewingColor.createdAt)}</p>
                            </div>
                            <div className="space-y-0.5">
                              <Label className="text-xs text-gray-500">Last Updated</Label>
                              <p className="text-xs text-gray-600">{formatDate(viewingColor.updatedAt)}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                

                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setIsViewDialogOpen(false);
                          handleEdit(viewingColor);
                        }}
                      >
                        <Edit className="w-4 h-4" />
                        Edit
                      </Button>
                      <Button
                        variant="danger"
                        size="sm"
                        onClick={() => {
                          setIsViewDialogOpen(false);
                          handleDelete(viewingColor._id);
                        }}
                      >
                        <Trash2 className="w-4 h-4" />
                        Delete
                      </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Search and Pagination Limit Dropdown */}
      <div className="flex flex-col gap-4 pt-0 py-1 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex gap-4 pt-0 py-1 flex-row sm:items-center w-full sm:max-w-[500px]">
          <div className="flex items-center gap-4">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <Input
                placeholder="Search colors..."
                value={search}
                onChange={(e) => handleSearch(e.target.value)}
                className="pl-10"
              />
                <X
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
              onClick={() => handleSearch('')}
            />
            </div>
            
            {/* PAGINATION LIMIT DROPDOWN */}
            <div className="flex items-center gap-2">
              <Label className="text-sm whitespace-nowrap">Show:</Label>
              <select
                value={limit.toString()}
                onChange={(e) => handleLimitChange(e.target.value)}
                className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
              >
                <option value="6">6</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
              </select>
            </div>
          </div>
        </div>
        <div className="pb-1 flex justify-between items-center">        
          <div className="flex items-center gap-3">
            {/* <div className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
              Total Colors: {pagination.total}
            </div> */}
            
            <Dialog open={isAddEditDialogOpen} onOpenChange={setIsAddEditDialogOpen}>
              <DialogTrigger asChild>
                <Button
                  onClick={() => {
                    setEditingColor(null);
                    resetForm();
                  }}
                  className="flex items-center gap-2"
                >
                  <Plus className="h-4 w-4 text-white" />
                  <span className="text-white">Add Color</span>
                </Button>
              </DialogTrigger>

              <DialogContent className="max-w-md">
                <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
                  <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                    <DialogHeader>
                      <DialogTitle>
                        {editingColor ? "Edit Color" : "Add New Color"}
                        
                      </DialogTitle>
                      <X className="h-6 w-6 p-1 text-white cursor-pointer"
                        onClick={() => {
                          setIsAddEditDialogOpen(false);
                          resetForm();
                        }}
                        />
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                      <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                        <div>
                          <Label className="mb-2 block">Name <span className="text-red">*</span></Label>
                          <Input
                            value={formData.name}
                            onChange={(e) => {
                              const value = e.target.value;

                              // Allow only letters, numbers, spaces
                              if (/^[A-Za-z0-9\s]*$/.test(value) || value === "") {
                                setFormData({ ...formData, name: value });
                              }
                            }}
                            onBlur={(e) => {
                              const trimmed = e.target.value.trim();
                              if (trimmed && !isValidColorName(trimmed)) {
                                toast.error("Only letters and numbers are allowed (no special characters)");
                              }
                            }}
                            placeholder="e.g. Red123, Blue Shade"
                            required
                          />
                        </div>
                        <div className="mb-3">
                          <Label className="mb-2 block">Color <span className="text-red">*</span></Label>
                          <div className="flex items-center gap-3">
                            <Input
                              type="color"
                              value={formData.hexCode}
                              onChange={(e) =>
                                setFormData({
                                  ...formData,
                                  hexCode: e.target.value,
                                })
                              }
                              className="w-14 h-10 p-1 cursor-pointer"
                            />
                            <Input
                              value={formData.hexCode}
                              onChange={(e) => {
                                let value = e.target.value;
                                if (!value.startsWith("#")) value = "#" + value;
                                setFormData({ ...formData, hexCode: value });
                              }}
                              placeholder="#RRGGBB"
                              required
                            />
                          </div>
                          <div className="mt-2 flex items-center gap-2">
                            <div
                              className="w-6 h-6 rounded border"
                              style={{ backgroundColor: formData.hexCode }}
                            />
                            <span className="text-sm text-gray-500">Preview</span>
                          </div>
                        </div>

                        <div className="flex items-center gap-2">
                          <Switch
                            checked={formData.isActive}
                            onCheckedChange={(v) =>
                              setFormData({ ...formData, isActive: v })
                            }
                            className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                          />
                          <Label>{formData.isActive ? "Active" : "Inactive"}</Label>
                        </div>
                      </div>

                      <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => setIsAddEditDialogOpen(false)}
                          className="border"
                        >
                          Cancel
                        </Button>
                        <Button type="submit">
                          {editingColor ? "Update" : "Create"}
                        </Button>
                      </div>
                    </form>
              
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="rounded-md  bg-white dark:bg-gray-900 mt-4">
        <Table className="bg-white border bg-white dark:bg-gray-900">
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className="bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800">
              {/* ID Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}

                </div>
              </TableHead>
              
              {/* Name Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("name")}
              >
                <div className="flex items-center justify-center gap-2">
                  Name
                  {sortField === "name" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              <TableHead className="text-center">Hex</TableHead>
              <TableHead className="text-center">Preview</TableHead>
              <TableHead className="text-center">Status</TableHead>
              <TableHead className="text-center">Action</TableHead>
            </TableRow>
          </TableHeader>

          <TableBody>
            {loading ? (
                <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                  <TableCell colSpan={6} className="px-4 py-8 text-center">
                    <div className="flex items-center justify-center">
                      <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                        <span className="ml-2">Loading...</span>
                      </div>
                  </TableCell>
                </TableRow>
              ) : colors.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      No colors found
                    </TableCell>
                  </TableRow>
              ) : (
              colors.map((color, index) => (
                <TableRow key={color._id} className="bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800">
                  <TableCell className="text-center">
                    {sortField === "createdAt" && sortOrder === "asc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index  // desc
                      : ((pagination.page - 1) * pagination.limit) + index + 1                 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center">
                    {color.name}
                  </TableCell>
                  <TableCell className="text-center">{color.hexCode}</TableCell>
                  <TableCell className="justify-center flex">
                    <div
                      className="w-6 h-6 rounded border"
                      style={{ backgroundColor: color.hexCode }}
                    />
                  </TableCell>
                  <TableCell className="text-center text-white">
                    <Badge
                      variant={color.isActive ? "default" : "secondary"}
                    >
                      {color.isActive ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-1">
                      <Tooltip text="View">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleView(color)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(color)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDelete(color._id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {/* Pagination */}
        {pagination.pages > 1 && (
          <div className="flex items-center justify-between mt-4 p-4">
            <div className="text-sm text-gray-500">
              Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} results
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="default"
                size="sm"
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </Button>
              <span className="text-sm">
                Page {page} of {pagination.pages}
              </span>
              <Button
                variant="default"
                size="sm"
                onClick={() => setPage(page + 1)}
                disabled={page === pagination.pages}
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}