// components/gifts/category-modal.tsx

import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useGifts } from "@/context/gift-context";
import {
  GiftCategory,
  GiftCategoryCreate,
  GiftCategoryUpdate,
} from "@/client/types.gen";
import { Loader2 } from "lucide-react";
import { useAuth } from "@/context/auth-context";

interface CategoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  categoryId?: string;
  eventId: string;
}

export function CategoryModal({
  isOpen,
  onClose,
  categoryId,
  eventId,
}: CategoryModalProps) {
  const {
    category,
    createCategory,
    updateCategory,
    fetchCategoryById,
    isLoadingCategory,
  } = useGifts();

  const { user } = useAuth();
  const isEditMode = Boolean(categoryId);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<GiftCategoryCreate | GiftCategoryUpdate>();

  // Load category data when editing
  useEffect(() => {
    if (isEditMode && categoryId) {
      fetchCategoryById(categoryId, eventId);
    }
  }, [isEditMode, categoryId, eventId, fetchCategoryById]);

  // Reset form when modal opens or category changes
  useEffect(() => {
    if (isOpen) {
      if (isEditMode && category) {
        reset({
          name: category.name,
          description: category.description,
          icon: category.icon,
          color: category.color,
        });
      } else {
        reset({
          name: "",
          description: "",
          icon: "",
          color: "#4f46e5", // Default color
        });
      }
    }
  }, [isOpen, category, isEditMode, reset]);

  const onSubmit = async (data: GiftCategoryCreate | GiftCategoryUpdate) => {
    try {
      if (isEditMode && categoryId) {
        await updateCategory(categoryId, data as GiftCategoryUpdate, eventId);
      } else {
        const createData = {
          ...data,
          created_by: user?.id, // This should be replaced with the actual user ID
        } as GiftCategoryCreate;

        await createCategory(createData);
      }
      onClose();
    } catch (error) {
      console.error("Error saving category:", error);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>
            {isEditMode ? "Edit Category" : "Add Category"}
          </DialogTitle>
        </DialogHeader>

        {isLoadingCategory && isEditMode ? (
          <div className="flex justify-center items-center py-8">
            <Loader2 className="h-8 w-8 animate-spin text-blue-500" />
          </div>
        ) : (
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right col-span-1">
                  Name
                </Label>
                <div className="col-span-3">
                  <Input
                    id="name"
                    placeholder="Category name"
                    {...register("name", { required: "Name is required" })}
                    className={errors.name ? "border-red-500" : ""}
                  />
                  {errors.name && (
                    <p className="text-red-500 text-sm mt-1">
                      {errors.name.message}
                    </p>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right col-span-1">
                  Description
                </Label>
                <div className="col-span-3">
                  <Textarea
                    id="description"
                    placeholder="Optional description"
                    {...register("description")}
                    className="min-h-[80px]"
                  />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="icon" className="text-right col-span-1">
                  Icon
                </Label>
                <div className="col-span-3">
                  <Input
                    id="icon"
                    placeholder="Icon name or URL"
                    {...register("icon")}
                  />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="color" className="text-right col-span-1">
                  Color
                </Label>
                <div className="col-span-3 flex gap-2 items-center">
                  <Input
                    id="color"
                    type="color"
                    className="w-12 h-8 p-0"
                    {...register("color")}
                  />
                  <Input
                    type="text"
                    placeholder="#RRGGBB"
                    className="flex-1"
                    {...register("color")}
                  />
                </div>
              </div>
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={onClose}>
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  <>{isEditMode ? "Update" : "Create"}</>
                )}
              </Button>
            </DialogFooter>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
}
