
"use client";

import { useState, useEffect, useActionState } from "react";
import Image from "next/image";
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 { CardContent, CardFooter } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { updateSiteSettings, type UpdateSiteSettingsFormState } from "@/lib/actions";
import type { SiteSettings } from "@/types";
import { LOGO_URL } from "@/constants"; // Fallback logo
import { ImageIcon, UploadCloud } from "lucide-react";
import { Separator } from "@/components/ui/separator";

const MAX_FILE_SIZE_SITE_ASSETS = 2 * 1024 * 1024; // 2MB for logo/favicon
const ACCEPTED_IMAGE_TYPES_SITE_ASSETS = ["image/png", "image/jpeg", "image/jpg", "image/webp", "image/svg+xml", "image/x-icon", "image/vnd.microsoft.icon"];

const settingsFormSchema = z.object({
  logoFile: z
    .custom<File | undefined>((val) => val === undefined || val === null || val instanceof File, "Invalid file.")
    .refine(
      (file) => !file || file.size <= MAX_FILE_SIZE_SITE_ASSETS,
      `Max logo file size is ${MAX_FILE_SIZE_SITE_ASSETS / (1024 * 1024)}MB.`
    )
    .refine(
      (file) => !file || ACCEPTED_IMAGE_TYPES_SITE_ASSETS.includes(file.type),
      "Invalid logo file type. Supported: PNG, JPG, WEBP, SVG, ICO."
    ).optional(),
  faviconFile: z
    .custom<File | undefined>((val) => val === undefined || val === null || val instanceof File, "Invalid file.")
    .refine(
      (file) => !file || file.size <= MAX_FILE_SIZE_SITE_ASSETS,
      `Max favicon file size is ${MAX_FILE_SIZE_SITE_ASSETS / (1024 * 1024)}MB.`
    )
    .refine(
      (file) => !file || ACCEPTED_IMAGE_TYPES_SITE_ASSETS.includes(file.type),
      "Invalid favicon file type. Supported: PNG, JPG, WEBP, SVG, ICO."
    ).optional(),
});

type SettingsFormValues = z.infer<typeof settingsFormSchema>;

interface SettingsFormProps {
  initialSettings: SiteSettings | null;
}

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

export function SettingsForm({ initialSettings }: SettingsFormProps) {
  const { toast } = useToast();
  const [state, formAction] = useActionState(updateSiteSettings, initialState);

  const [logoPreview, setLogoPreview] = useState<string | null>(initialSettings?.logoUrl || LOGO_URL);
  const [faviconPreview, setFaviconPreview] = useState<string | null>(initialSettings?.faviconUrl || "/favicon.ico");

  const form = useForm<SettingsFormValues>({
    resolver: zodResolver(settingsFormSchema),
    defaultValues: {
      logoFile: undefined,
      faviconFile: undefined,
    },
  });

  useEffect(() => {
    if (state.message) {
      if (state.success) {
        toast({
          title: "Success!",
          description: state.message,
        });
        form.reset({ logoFile: undefined, faviconFile: undefined }); 
        // If action returns updated settings, update previews here
        // For now, a page refresh might be needed to see new previews if initialSettings aren't re-fetched client-side
      } else {
        toast({
          title: "Error Updating Settings",
          description: state.message || "An unexpected error occurred.",
          variant: "destructive",
        });
        if (state.errors?.logoFile && !form.formState.errors.logoFile) form.setError("logoFile", { message: state.errors.logoFile[0] });
        if (state.errors?.faviconFile && !form.formState.errors.faviconFile) form.setError("faviconFile", { message: state.errors.faviconFile[0] });
      }
    }
  }, [state, toast, form]);
  
  useEffect(() => {
    setLogoPreview(initialSettings?.logoUrl || LOGO_URL);
    setFaviconPreview(initialSettings?.faviconUrl || "/favicon.ico");
  }, [initialSettings]);

  const handleFileChange = (
    event: React.ChangeEvent<HTMLInputElement>,
    rhfOnChange: (file: File | undefined) => void,
    setPreview: React.Dispatch<React.SetStateAction<string | null>>,
    fieldName: 'logoFile' | 'faviconFile'
  ) => {
    const file = event.target.files?.[0];
    rhfOnChange(file || undefined); // Update RHF state with the File object or undefined

    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    } else {
      if (fieldName === 'logoFile') {
        setPreview(initialSettings?.logoUrl || LOGO_URL);
      } else if (fieldName === 'faviconFile') {
        setPreview(initialSettings?.faviconUrl || "/favicon.ico");
      }
    }
  };

  return (
    <Form {...form}>
      <form action={formAction} className="space-y-8">
        <CardContent className="space-y-6">
          {/* Logo Section */}
          <div className="space-y-3 p-4 border rounded-lg">
            <h3 className="text-lg font-medium text-foreground">Site Logo</h3>
            <div className="flex flex-col sm:flex-row items-center gap-4">
              <div className="w-24 h-24 rounded-md border bg-muted flex items-center justify-center overflow-hidden">
                {logoPreview ? (
                  <Image src={logoPreview} alt="Current Site Logo" width={96} height={96} className="object-contain" />
                ) : (
                  <ImageIcon className="w-12 h-12 text-muted-foreground" />
                )}
              </div>
              <div className="flex-grow">
                <FormField
                  control={form.control}
                  name="logoFile"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel htmlFor={field.name}>Upload New Logo</FormLabel>
                      <FormControl>
                        <Input
                          id={field.name}
                          type="file"
                          accept={ACCEPTED_IMAGE_TYPES_SITE_ASSETS.join(',')}
                          name={field.name} // Ensures name attribute is set for FormData
                          onChange={(e) => handleFileChange(e, field.onChange, setLogoPreview, 'logoFile')}
                          onBlur={field.onBlur}
                          ref={field.ref}
                          className="mt-1"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <p className="text-xs text-muted-foreground mt-1">Recommended: PNG, JPG, SVG. Max size: 2MB.</p>
              </div>
            </div>
          </div>

          <Separator />

          {/* Favicon Section */}
          <div className="space-y-3 p-4 border rounded-lg">
            <h3 className="text-lg font-medium text-foreground">Site Favicon</h3>
             <div className="flex flex-col sm:flex-row items-center gap-4">
              <div className="w-16 h-16 rounded-md border bg-muted flex items-center justify-center overflow-hidden">
                {faviconPreview ? (
                  <Image src={faviconPreview} alt="Current Site Favicon" width={64} height={64} className="object-contain" />
                ) : (
                  <ImageIcon className="w-8 h-8 text-muted-foreground" />
                )}
              </div>
              <div className="flex-grow">
                <FormField
                  control={form.control}
                  name="faviconFile"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel htmlFor={field.name}>Upload New Favicon</FormLabel>
                      <FormControl>
                        <Input
                          id={field.name}
                          type="file"
                          accept={ACCEPTED_IMAGE_TYPES_SITE_ASSETS.join(',')}
                          name={field.name} // Ensures name attribute is set for FormData
                          onChange={(e) => handleFileChange(e, field.onChange, setFaviconPreview, 'faviconFile')}
                          onBlur={field.onBlur}
                          ref={field.ref}
                           className="mt-1"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <p className="text-xs text-muted-foreground mt-1">Recommended: ICO, PNG (e.g., 32x32px). Max size: 2MB.</p>
              </div>
            </div>
          </div>
        </CardContent>
        <CardFooter className="border-t px-6 py-4">
          <Button type="submit" disabled={form.formState.isSubmitting || (!form.getValues("logoFile") && !form.getValues("faviconFile"))}>
            {form.formState.isSubmitting ? "Saving..." : <><UploadCloud className="mr-2 h-4 w-4" /> Save Settings</>}
          </Button>
        </CardFooter>
      </form>
    </Form>
  );
}
