
"use client";

import { useState, useEffect, useActionState } from "react";
import { useForm, type SubmitHandler } 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 { Textarea } from "@/components/ui/textarea";
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 { addProject, type AddProjectFormState } from "@/lib/actions";
import { PlusCircle } from "lucide-react";
import { useRouter } from 'next/navigation'; // Import useRouter

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

const projectFormSchema = z.object({
  title: z.string().min(3, { message: "Title must be at least 3 characters." }),
  organization: z.string().min(3, { message: "Organization must be at least 3 characters." }),
  description: z.string().min(10, { message: "Description must be at least 10 characters." }),
  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, and .webp formats are supported."
    ),
  imageHint: z.string().min(2, { message: "Image hint must be at least 2 characters." }).max(50, { message: "Image hint is too long (max 50 characters)."}),
  impact: z.string().min(5, { message: "Please provide at least one impact point. Separate multiple points with a comma." }),
});

type ProjectFormValues = z.infer<typeof projectFormSchema>;

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

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

  const form = useForm<ProjectFormValues>({
    resolver: zodResolver(projectFormSchema),
    defaultValues: {
      title: "",
      organization: "",
      description: "",
      imageFile: undefined, 
      imageHint: "",
      impact: "",
    },
  });

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


  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button>
          <PlusCircle className="mr-2 h-5 w-5" /> Add New Project
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Add New Project</DialogTitle>
          <DialogDescription>
            Fill in the details for the new project. Click save when you&apos;re done.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form
            action={formAction} 
            className="space-y-4 py-4"
          >
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Project Title</FormLabel>
                  <FormControl>
                    <Input placeholder="E.g., Rural Financial Inclusion" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="organization"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Organization</FormLabel>
                  <FormControl>
                    <Input placeholder="E.g., World Vision" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea placeholder="Detailed description of the project..." {...field} rows={4} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="imageFile"
              render={({ field: { onChange, value, ...restField } }) => ( 
                <FormItem>
                  <FormLabel>Project Image</FormLabel>
                  <FormControl>
                    <Input 
                      type="file" 
                      accept="image/png, image/jpeg, image/jpg, image/webp"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        onChange(file); 
                      }}
                      {...restField} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="imageHint"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Image Hint (for AI search, 1-2 words)</FormLabel>
                  <FormControl>
                    <Input placeholder="E.g., community finance" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="impact"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Key Impact Points (comma-separated)</FormLabel>
                  <FormControl>
                    <Textarea placeholder="E.g., Increased literacy, Digitized operations, Empowered locals" {...field} rows={3}/>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <DialogClose asChild>
                <Button type="button" variant="outline">Cancel</Button>
              </DialogClose>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting ? "Saving..." : "Save Project"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
