import { useState, useMemo } from "react";
import { apiFetch } from '@/utils/api';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { TemplateForm } from "@/components/templates/TemplateForm";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { ArrowUpDown, Pencil, Trash2, Copy } from "lucide-react";
import config from "@/config";
import {
  useReactTable,
  getCoreRowModel,
  getSortedRowModel,
  SortingState,
  flexRender,
  type ColumnDef,
} from "@tanstack/react-table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { SearchProductTemplateDialog } from "@/components/templates/SearchProductTemplateDialog";
import { toast } from "sonner";

interface FieldOption {
  label: string;
  value: string;
  type?: number;
  level?: number;
  hexColor?: string;
}

interface FieldOptions {
  companies: FieldOption[];
  artists: FieldOption[];
  sizes: FieldOption[];
  themes: FieldOption[];
  categories: FieldOption[];
  colors: FieldOption[];
  suppliers: FieldOption[];
  taxCategories: FieldOption[];
  shippingRestrictions: FieldOption[];
}

interface Template {
  id: number;
  company: string;
  product_type: string;
  supplier?: string;
  msrp?: number;
  cost_each?: number;
  qty_per_unit?: number;
  case_qty?: number;
  hts_code?: string;
  description?: string;
  weight?: number;
  length?: number;
  width?: number;
  height?: number;
  tax_cat?: string;
  size_cat?: string;
  categories?: string[];
  ship_restrictions?: string[];
  created_at: string;
  updated_at: string;
}

export function TemplateManagement() {
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [templateToDelete, setTemplateToDelete] = useState<Template | null>(null);
  const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);
  const [sorting, setSorting] = useState<SortingState>([]);
  const [searchQuery, setSearchQuery] = useState("");

  const queryClient = useQueryClient();

  const { data: templates, isLoading } = useQuery<Template[]>({
    queryKey: ["templates"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/templates`);
      if (!response.ok) {
        throw new Error("Failed to fetch templates");
      }
      return response.json();
    },
  });

  const { data: fieldOptions } = useQuery<FieldOptions>({
    queryKey: ["fieldOptions"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/import/field-options`);
      if (!response.ok) {
        throw new Error("Failed to fetch field options");
      }
      return response.json();
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await apiFetch(`${config.apiUrl}/templates/${id}`, {
        method: "DELETE",
      });
      if (!response.ok) {
        throw new Error("Failed to delete template");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      toast.success("Template deleted successfully");
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : "Failed to delete template");
    },
  });

  const handleEdit = (template: Template) => {
    setEditingTemplate(template);
  };

  const handleCopy = (template: Template) => {
    // Remove id and timestamps for copy operation
    const { id, created_at, updated_at, ...templateData } = template;
    // Set as new template with empty product type
    setEditingTemplate({
      ...templateData,
      product_type: '',
      id: 0 // Add a temporary ID to indicate it's a copy
    } as Template);
  };

  const handleDeleteClick = (template: Template) => {
    setTemplateToDelete(template);
    setIsDeleteOpen(true);
  };

  const handleDeleteConfirm = () => {
    if (templateToDelete) {
      deleteMutation.mutate(templateToDelete.id);
      setIsDeleteOpen(false);
      setTemplateToDelete(null);
    }
  };

  const handleTemplateSuccess = () => {
    queryClient.invalidateQueries({ queryKey: ["templates"] });
  };

  const columns = useMemo<ColumnDef<Template>[]>(() => [
    {
      accessorKey: "company",
      header: ({ column }) => (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Company
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      ),
      cell: ({ row }) => {
        const companyId = row.getValue("company");
        return fieldOptions?.companies.find(c => c.value === companyId)?.label || companyId;
      },
    },
    {
      accessorKey: "product_type",
      header: ({ column }) => (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Product Type
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      ),
    },
    {
      accessorKey: "updated_at",
      header: ({ column }) => (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Last Updated
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      ),
      cell: ({ row }) => new Date(row.getValue("updated_at")).toLocaleDateString(),
    },
    {
      id: "actions",
      cell: ({ row }) => (
        <div className="flex gap-2 justify-end pr-4">
          <Button
            variant="ghost"
            onClick={() => handleEdit(row.original)}
          >
            <Pencil className="h-4 w-4" />
            Edit
          </Button>
          <Button
            variant="ghost"
            onClick={() => handleCopy(row.original)}
          >
            <Copy className="h-4 w-4" />
            Copy
          </Button>
          <Button
            variant="ghost"
            className="text-destructive hover:text-destructive"
            onClick={() => handleDeleteClick(row.original)}
          >
            <Trash2 className="h-4 w-4" />
            Delete
          </Button>
        </div>
      ),
    },
  ], [fieldOptions]);

  const filteredData = useMemo(() => {
    if (!templates) return [];
    return templates.filter((template) => {
      const searchString = searchQuery.toLowerCase();
      return (
        template.company.toLowerCase().includes(searchString) ||
        template.product_type.toLowerCase().includes(searchString) ||
        (template.supplier?.toLowerCase().includes(searchString) ?? false)
      );
    });
  }, [templates, searchQuery]);

  const table = useReactTable({
    data: filteredData,
    columns,
    state: {
      sorting,
    },
    onSortingChange: setSorting,
    getSortedRowModel: getSortedRowModel(),
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">Import Templates</h2>
        <div className="flex gap-2">
          <Button onClick={() => setIsCreateOpen(true)}>
            Create Blank Template
          </Button>
          <Button onClick={() => setIsSearchOpen(true)}>
            Create from Product
          </Button>
        </div>
      </div>

      <div className="flex items-center gap-4">
        <Input
          placeholder="Search templates..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="max-w-sm"
        />
      </div>

      {isLoading ? (
        <div>Loading templates...</div>
      ) : (
        <div className="border rounded-lg">
          <Table>
            <TableHeader className="bg-muted">
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableHead key={header.id}>
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                    </TableHead>
                  ))}
                </TableRow>
              ))}
            </TableHeader>
            <TableBody>
              {table.getRowModel().rows?.length ? (
                table.getRowModel().rows.map((row) => (
                  <TableRow key={row.id} className="hover:bg-gray-100">
                    {row.getVisibleCells().map((cell) => (
                      <TableCell key={cell.id} className="pl-6">
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={columns.length} className="text-center">
                    No templates found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Template Form for Create/Edit/Copy */}
      <TemplateForm
        isOpen={isCreateOpen || (editingTemplate !== null)}
        onClose={() => {
          setIsCreateOpen(false);
          setEditingTemplate(null);
        }}
        onSuccess={handleTemplateSuccess}
        initialData={editingTemplate || null}
        mode={editingTemplate ? (editingTemplate.id ? 'edit' : 'copy') : 'create'}
        templateId={editingTemplate?.id}
        fieldOptions={fieldOptions || null}
      />

      {/* Product Search Dialog */}
      <SearchProductTemplateDialog
        isOpen={isSearchOpen}
        onClose={() => setIsSearchOpen(false)}
        onTemplateCreated={handleTemplateSuccess}
      />

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Template</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this template? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setIsDeleteOpen(false);
              setTemplateToDelete(null);
            }}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteConfirm}>
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
