"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { CircleDashed, Edit, Plus, Search, Trash, Upload } from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useDispatch, useSelector } from "react-redux";
// import {
//   fetchCategories,
//   createCategory,
//   updateCategory,
//   deleteCategory,
// } from "@/redux/features/categoriesSlice";
// import { RootState, AppDispatch } from "@/redux/store";
import {
  useCreateCategoryMutation,
  useDeleteCategoryMutation,
  useGetCategoriesQuery,
  useUpdateCategoryMutation,
} from "@/redux/services/categories.api";
import { useRouter } from "next/navigation";
import Image from "next/image";

type Category = {
  _id: string;
  name: string;
  icon: string; // URL or empty string
  status: string; // 'active' or other status
};

const FormSchema = z.object({
  name: z.string().min(2, { message: "Name must be at least 2 characters." }),
  icon: z.string().optional(),
});

export default function CategoriesManagement() {
  // const router = useRouter();
  // useEffect(() => {
  //   const token = localStorage.getItem("token");
  //   if (!token) {
  //     router.push("/");
  //   }
  // });
  const {
    data: categories,
    isLoading: isCategoryLoading,
    error: categoryError,
  } = useGetCategoriesQuery();
  const [createCategory, { isLoading, error }] = useCreateCategoryMutation({});
  const [updateCategory, { isLoading: updateLoading, error: updateerror }] =
    useUpdateCategoryMutation({});
  const [deleteCategory, { isLoading: deleteLoading, error: deleteerror }] =
    useDeleteCategoryMutation({});

  // const dispatch = useDispatch<AppDispatch>();
  const fileInputRef = useRef<HTMLInputElement>(null);
  // const categories = useSelector(
  //   (state: RootState) => state.categories.categories
  // );
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(
    null
  );
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    mode: "onChange",
    defaultValues: {
      name: "",
      icon: "",
    },
  });

  // useEffect(() => {
  //   dispatch(fetchCategories());
  // }, [dispatch]);

  useEffect(() => {
    form.reset({
      name: selectedCategory?.name || "",
      icon: selectedCategory?.icon || "",
    });
  }, [selectedCategory, form]);

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        form.setValue("icon", reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCreateCategory = (values: z.infer<typeof FormSchema>) => {
    const formData = new FormData();
    formData.append("name", values.name);
    const file = fileInputRef.current?.files?.[0];
    if (file) {
      formData.append("icon", file);
    }
    // const {data, error} = await createCategory()
    createCategory(formData)
      .unwrap()
      .then((res) => {
        if (res.status) {
          setIsCreateDialogOpen(false);
          return toast({
            title: res.message,
            variant: "success",
          });
        }
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err) => console.log("err", err));
    // dispatch(createCategory(formData))
    //   .unwrap()
    //   .then(() => {
    //     setIsCreateDialogOpen(false);
    //     toast({ title: "Category created successfully", variant: "default" });
    //   })
    //   .catch(() => {
    //     toast({ title: "Error creating category", variant: "destructive" });
    //   });
  };

  const handleUpdateCategory = (values: z.infer<typeof FormSchema>) => {
    if (!selectedCategory) return;
    const formData = new FormData();
    formData.append("name", values.name);
    formData.append("categoryId", selectedCategory._id!);
    const file = fileInputRef.current?.files?.[0];
    if (file) {
      formData.append("icon", file);
    }
    updateCategory(formData)
      .unwrap()
      .then((res: any) => {
        if (res.status) {
          setIsCreateDialogOpen(false);
          setSelectedCategory(null);
          return toast({
            title: res.message,
            variant: "success",
          });
        }
        setSelectedCategory(null);
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err: any) => console.log("err", err));
  };

  const handleDeleteCategory = (id: string) => {
    deleteCategory(id)
      .unwrap()
      .then((res: any) => {
        if (res.status) {
          setIsCreateDialogOpen(false);
          return toast({
            title: res.message,
            variant: "destructive",
          });
        }
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err: any) => console.log("err", err));

    //  dispatch(updateCategory(id))
    //    .unwrap()
    //    .then(() => {
    //      setSelectedCategory(null);
    //      toast({ title: "Category updated successfully", variant: "default" });
    //    })
    //    .catch(() => {
    //      toast({ title: "Error updating category", variant: "destructive" });
    //    });
  };
  // if (categories) {

  const filteredCategories: Category[] =
    categories && categories.length >= 0
      ? categories.filter(
          (category) =>
            category.name && // Ensure category.name is defined
            category.name.toLowerCase().includes(searchTerm.toLowerCase())
        )
      : [];

  return (
    <div className="container mx-auto p-4">
      {/* Search and Create UI */}
      <div className="flex justify-between items-center mb-4">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400" />
          <Input
            type="text"
            placeholder="Search categories..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-8"
          />
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button
              variant={"appVariant"}
              onClick={() => {
                setIsCreateDialogOpen(true);
                form.reset();
              }}
            >
              <Plus className="mr-2 h-4 w-4" />
              Create New Category
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create New Category</DialogTitle>
              <DialogDescription>
                Enter the details for the new category.
              </DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(handleCreateCategory)}
                className="space-y-4"
              >
                {/* Form Fields */}
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="Category Name" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormItem>
                  <FormLabel>Profile Picture (Optional)</FormLabel>
                  <FormControl>
                    <div className="flex items-center gap-2">
                      <Input
                        id="profilePicture"
                        type="file"
                        accept="image/*"
                        onChange={handleFileUpload}
                        className="hidden"
                        ref={fileInputRef}
                      />
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => fileInputRef.current?.click()}
                      >
                        <Upload className="mr-2 h-4 w-4" />
                        Upload
                      </Button>
                      {form.watch("icon") && (
                        <Avatar>
                          <AvatarImage
                            src={form.watch("icon")}
                            alt={form.watch("name")}
                          />
                          <AvatarFallback>
                            {form.watch("name")?.charAt(0)}
                          </AvatarFallback>
                        </Avatar>
                      )}
                    </div>
                  </FormControl>
                </FormItem>
                <DialogFooter>
                  {!form.formState.isValid ? (
                    <Button
                      variant="appVariant"
                      type="submit"
                      // disabled={!form.formState.isValid}
                    >
                      Create Category
                    </Button>
                  ) : (
                    <Button
                      variant="appVariant"
                      // disabled={!form.formState.isValid}
                    >
                      Create Category
                    </Button>
                  )}
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      {/* Categories Table */}
      <Card>
        <CardHeader>
          <CardTitle>Categories</CardTitle>
          <CardDescription>Manage your product categories</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Category</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredCategories &&
                filteredCategories.map((category) => (
                  <TableRow key={category._id}>
                    <TableCell className="font-medium">
                      <div className="flex items-center space-x-2">
                        <Avatar>
                          {category.icon && category.icon.length > 0 ? (
                            <Image
                              src={category.icon}
                              height={200}
                              width={200}
                              alt="BI"
                            />
                          ) : (
                            <AvatarFallback>
                              {category?.name.charAt(0)}
                            </AvatarFallback>
                          )}
                        </Avatar>
                        {/* <Avatar>
                          <AvatarImage
                            src={category.icon}
                            alt={category.name}
                          />
                          <AvatarFallback>
                            {category.name.charAt(0)}
                          </AvatarFallback>
                        </Avatar> */}
                        <span>{category.name}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex space-x-2">
                        <Button
                          variant="outline"
                          size="icon"
                          onClick={() => setSelectedCategory(category)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="outline" size="icon">
                              <Trash className="h-4 w-4 text-red-800" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                              <AlertDialogDescription>
                                This action cannot be undone. This will
                                permanently delete the category.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>Cancel</AlertDialogCancel>
                              <AlertDialogAction
                                className="bg-[#8f0029]"
                                onClick={() =>
                                  handleDeleteCategory(category._id!)
                                }
                              >
                                Delete
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
          {isCategoryLoading && (
            <div>
              <div className="flex justify-center items-center h-[50vh]">
                <CircleDashed className="animate-spin text-[#be063f]" />
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Edit Category Dialog */}
      {selectedCategory && (
        <Dialog
          open={!!selectedCategory}
          onOpenChange={() => setSelectedCategory(null)}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Edit Category: {selectedCategory.name}</DialogTitle>
              <DialogDescription>
                Update the details for this category.
              </DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(handleUpdateCategory)}
                className="space-y-4"
              >
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="Category Name" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormItem>
                  <FormLabel>Profile Picture (Optional)</FormLabel>
                  <FormControl>
                    <div className="flex items-center gap-2">
                      <Input
                        id="profilePicture"
                        type="file"
                        accept="image/*"
                        onChange={handleFileUpload}
                        className="hidden"
                        ref={fileInputRef}
                      />
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => fileInputRef.current?.click()}
                      >
                        <Upload className="mr-2 h-4 w-4" />
                        Upload
                      </Button>
                      {form.watch("icon") && (
                        <Avatar>
                          <AvatarImage
                            src={form.watch("icon")}
                            alt={form.watch("name")}
                          />
                          <AvatarFallback>
                            {form.watch("name")?.charAt(0)}
                          </AvatarFallback>
                        </Avatar>
                      )}
                    </div>
                  </FormControl>
                </FormItem>
                <DialogFooter>
                  <Button variant="appVariant" type="submit">
                    Update Category
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
