
"use client";

import { useState, useEffect, useActionState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogClose,
} from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { uploadGeneralTariImage, type UploadGeneralImageFormState } from "@/lib/actions";
import { PlusCircle, UploadCloud } from "lucide-react";
import { useRouter } from 'next/navigation';
import { TARI_GENERAL_IMAGES_FOLDER } from "@/constants";

const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"];

const imageUploadSchema = z.object({
  imageFile: z
    .custom<File>((val) => val instanceof File, "Please upload an image file.")
    .refine((file) => file?.size <= MAX_FILE_SIZE, `Max file size is 5MB.`)
    .refine(
      (file) => ACCEPTED_IMAGE_TYPES.includes(file?.type),
      "Only .jpg, .jpeg, .png, .webp, and .gif formats are supported."
    ),
});

type ImageUploadFormValues = z.infer<typeof imageUploadSchema>;

const initialState: UploadGeneralImageFormState = {
  message: "",
  success: false,
};

export function UploadImageForm() {
  const [isOpen, setIsOpen] = useState(false);
  const { toast } = useToast();
  const [state, formAction] = useActionState(uploadGeneralTariImage, initialState);
  const router = useRouter();

  const form = useForm<ImageUploadFormValues>({
    resolver: zodResolver(imageUploadSchema),
    defaultValues: {
      imageFile: undefined, 
    },
  });

  useEffect(() => {
    if (state.message) {
      if (state.success) {
        toast({
          title: "Success!",
          description: state.message,
        });
        form.reset();
        setIsOpen(false);
        router.refresh(); 
      } else {
        toast({
          title: "Error Uploading Image",
          description: state.message || state.errors?.general?.[0] || "An unexpected error occurred.",
          variant: "destructive",
        });
        if (state.errors?.imageFile && !form.formState.errors.imageFile) form.setError("imageFile", { message: state.errors.imageFile[0] as string });
      }
    }
  }, [state, toast, form, router]);


  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button>
          <UploadCloud className="mr-2 h-5 w-5" /> Upload New Image
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Upload New Image</DialogTitle>
          <DialogDescription>
            Select an image file to upload to the &quot;{TARI_GENERAL_IMAGES_FOLDER}&quot; folder on Tari.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form
            action={formAction} 
            className="space-y-6 py-4"
          >
            <FormField
              control={form.control}
              name="imageFile"
              render={({ field: { onChange, value, ...restField } }) => ( 
                <FormItem>
                  <FormLabel>Image File</FormLabel>
                  <FormControl>
                    <Input 
                      type="file" 
                      accept={ACCEPTED_IMAGE_TYPES.join(',')}
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        onChange(file); 
                      }}
                      {...restField} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <DialogClose asChild>
                <Button type="button" variant="outline">Cancel</Button>
              </DialogClose>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting ? "Uploading..." : "Upload Image"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
