
"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 { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogClose,
} from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { updateProject, type UpdateProjectFormState } from "@/lib/actions";
import type { Project } from "@/types";
import { useRouter } from 'next/navigation';
import Image from "next/image";

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

// Schema for client-side validation
const editProjectFormSchema = 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."
    ).optional(), // Image file is optional for updates
  imageHint: z.string().min(2, { message: "Image hint must be at least 2 characters." }).max(50, { message: "Image hint is too long."}),
  impact: z.string().min(5, { message: "Please provide at least one impact point. Separate multiple points with a comma." }),
});

type EditProjectFormValues = z.infer<typeof editProjectFormSchema>;

interface EditProjectFormProps {
  project: Project;
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
}

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

export function EditProjectForm({ project, isOpen, onOpenChange }: EditProjectFormProps) {
  const { toast } = useToast();
  const router = useRouter();
  
  // Bind projectId to the server action
  const updateProjectWithId = updateProject.bind(null, project.id);
  const [state, formAction] = useActionState(updateProjectWithId, initialState);

  const form = useForm<EditProjectFormValues>({
    resolver: zodResolver(editProjectFormSchema),
    defaultValues: {
      title: project.title || "",
      organization: project.organization || "",
      description: project.description || "",
      imageFile: undefined,
      imageHint: project.imageHint || "",
      impact: project.impact?.join(", ") || "",
    },
  });
  
  // Reset form and state when dialog closes or project changes
  useEffect(() => {
    if (!isOpen) {
      form.reset({
        title: project.title || "",
        organization: project.organization || "",
        description: project.description || "",
        imageFile: undefined,
        imageHint: project.imageHint || "",
        impact: project.impact?.join(", ") || "",
      });
      // It's important to reset the action state if it's managed per dialog instance
      // or if the `initialState` reference is the same across calls.
      // For this component, since `initialState` is constant, there's no explicit reset needed for `state` itself.
    } else {
       // When dialog opens, re-initialize default values in case project prop changed
       form.reset({
        title: project.title || "",
        organization: project.organization || "",
        description: project.description || "",
        imageFile: undefined,
        imageHint: project.imageHint || "",
        impact: project.impact?.join(", ") || "",
      });
    }
  }, [isOpen, project, form]);


  useEffect(() => {
    if (state.message) {
      if (state.success) {
        toast({
          title: "Success!",
          description: state.message,
        });
        onOpenChange(false); // Close dialog on success
        router.refresh(); 
      } else {
        toast({
          title: "Error Updating Project",
          description: state.message || state.errors?.general?.[0] || "An unexpected error occurred.",
          variant: "destructive",
        });
        // Set form errors from server action state
        if (state.errors?.title) form.setError("title", { message: state.errors.title[0] });
        if (state.errors?.organization) form.setError("organization", { message: state.errors.organization[0] });
        if (state.errors?.description) form.setError("description", { message: state.errors.description[0] });
        if (state.errors?.imageFile) form.setError("imageFile", { message: state.errors.imageFile[0] as string });
        if (state.errors?.imageHint) form.setError("imageHint", { message: state.errors.imageHint[0] });
        if (state.errors?.impact) form.setError("impact", { message: state.errors.impact[0] });
      }
    }
  }, [state, toast, form, onOpenChange, router]);
  
  const currentImageSrc = (project.imageUrl && (project.imageUrl.startsWith('/') || project.imageUrl.startsWith('http')))
                          ? project.imageUrl
                          : `https://placehold.co/100x100.png?text=No+Img`;


  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Edit Project: {project.title}</DialogTitle>
          <DialogDescription>
            Modify the project details below. 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>
              )}
            />
            <FormItem>
              <FormLabel>Current Image</FormLabel>
              <div className="mt-1">
                <Image 
                  src={currentImageSrc} 
                  alt={`Current image for ${project.title}`} 
                  width={100} 
                  height={100} 
                  className="rounded-md object-cover border"
                  onError={(e) => { e.currentTarget.srcset = `https://placehold.co/100x100.png?text=Error`; e.currentTarget.src = `https://placehold.co/100x100.png?text=Error`; }}
                />
              </div>
            </FormItem>
            <FormField
              control={form.control}
              name="imageFile"
              render={({ field: { onChange, value, ...restField } }) => ( 
                <FormItem>
                  <FormLabel>Upload New Image (Optional)</FormLabel>
                  <FormControl>
                    <Input 
                      type="file" 
                      accept="image/png, image/jpeg, image/jpg, image/webp"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        onChange(file || undefined); 
                      }}
                      {...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" onClick={() => onOpenChange(false)}>Cancel</Button>
              </DialogClose>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting ? "Saving..." : "Save Changes"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
