import { useState } from "react";
import { Pencil, Trash2 } from "lucide-react";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { useLocalizedName } from "@/shared/common/localizedName";
import { ColumnDef } from "@tanstack/react-table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { Textarea } from "@/shared/common/ui/textarea";
import {
  useServiceCategoryList,
  useServiceCategoryMutations,
} from "../../hooks/useServiceCategory";
import { ServiceCategory } from "../../services/api/serviceCategoryService";

interface ServiceCategoryListProps {
  organizationId: string;
  extraToolbar?: React.ReactNode;
}

export const ServiceCategoryList = ({
  organizationId,
  extraToolbar,
}: ServiceCategoryListProps) => {
  const [pageIndex, setPageIndex] = useState(0);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [selectedCategory, setSelectedCategory] =
    useState<ServiceCategory | null>(null);
  const localizedName = useLocalizedName();

  // Form state
  const [formData, setFormData] = useState({
    slug: "",
    name: { am: "", en: "" },
    description: { am: "", en: "" },
  });

  const { data, isLoading, isError, refetch } =
    useServiceCategoryList(organizationId);
  const { update, delete: deleteCategory } = useServiceCategoryMutations();

  const handleEdit = (category: ServiceCategory) => {
    setSelectedCategory(category);
    setFormData({
      slug: category.slug,
      name: category.name,
      description: category.description,
    });
    setIsEditOpen(true);
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!organizationId || !selectedCategory) return;

    update.mutate(
      {
        id: selectedCategory.id,
        data: {
          ...formData,
          organizationId,
        },
      },
      {
        onSuccess: () => {
          setIsEditOpen(false);
          setSelectedCategory(null);
          setFormData({
            slug: "",
            name: { am: "", en: "" },
            description: { am: "", en: "" },
          });
        },
      }
    );
  };

  const handleDeleteClick = (category: ServiceCategory) => {
    setSelectedCategory(category);
    setIsDeleteOpen(true);
  };

  const handleDelete = () => {
    if (!selectedCategory) return;

    deleteCategory.mutate(selectedCategory.id, {
      onSuccess: () => {
        setIsDeleteOpen(false);
        setSelectedCategory(null);
      },
    });
  };

  const columns: ColumnDef<ServiceCategory>[] = [
    {
      accessorKey: "slug",
      header: "Slug",
    },
    {
      accessorKey: "name",
      header: "Name",
      cell: ({ row }) => localizedName(row.original.name),
    },
    {
      accessorKey: "description",
      header: "Description",
      cell: ({ row }) => localizedName(row.original.description),
    },
    {
      id: "actions",
      header: "Actions",
      cell: ({ row }) => (
        <div className="flex gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleEdit(row.original)}
          >
            <Pencil className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleDeleteClick(row.original)}
          >
            <Trash2 className="h-4 w-4 text-destructive" />
          </Button>
        </div>
      ),
    },
  ];

  if (isLoading)
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-12 w-full" />
        <Skeleton className="h-12 w-full" />
      </div>
    );

  if (isError)
    return (
      <div className="p-6 space-y-4">
        <p className="text-destructive font-semibold">
          Failed to load service categories
        </p>
        <Button onClick={() => refetch()}>Retry</Button>
      </div>
    );

  const serviceCategories = data?.data?.items || [];

  return (
    <div className="p-6">
      <AdvancedTable<ServiceCategory, unknown>
        columns={columns}
        data={serviceCategories}
        tableName="Service Categories"
        extraToolbar={extraToolbar}
        toolBarPosition="right"
        itemCount={serviceCategories.length}
        pageIndex={pageIndex}
        onPageChange={setPageIndex}
        nextFunction={() => setPageIndex((p) => p + 1)}
        prevFunction={() => setPageIndex((p) => Math.max(0, p - 1))}
        refresh={refetch}
      />

      {/* Edit Dialog */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit Service Category</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleUpdate} className="space-y-4">
            <div>
              <Label>Slug</Label>
              <Input
                value={formData.slug}
                onChange={(e) =>
                  setFormData({ ...formData, slug: e.target.value })
                }
                required
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Name (English)</Label>
                <Input
                  value={formData.name.en}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      name: { ...formData.name, en: e.target.value },
                    })
                  }
                  required
                />
              </div>
              <div>
                <Label>Name (Amharic)</Label>
                <Input
                  value={formData.name.am}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      name: { ...formData.name, am: e.target.value },
                    })
                  }
                  required
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Description (English)</Label>
                <Textarea
                  value={formData.description.en}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      description: {
                        ...formData.description,
                        en: e.target.value,
                      },
                    })
                  }
                  required
                />
              </div>
              <div>
                <Label>Description (Amharic)</Label>
                <Textarea
                  value={formData.description.am}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      description: {
                        ...formData.description,
                        am: e.target.value,
                      },
                    })
                  }
                  required
                />
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsEditOpen(false)}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={update.isPending}>
                {update.isPending ? "Updating..." : "Update"}
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Service Category</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete "
              {selectedCategory && localizedName(selectedCategory.name)}"? This
              action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleteCategory.isPending}
              className="bg-destructive text-white hover:bg-destructive/90"
            >
              {deleteCategory.isPending ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
