"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import React, { useEffect, useState } from "react"
import Image from "next/image"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { toast } from "@/hooks/use-toast"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "../ui/card"
import { Textarea } from "../ui/textarea"
import { getShopProfile, setShopProfile, getLoginCredentials, setLoginCredentials, type ShopProfile, type LoginCredentials } from "@/lib/data"
import { Separator } from "../ui/separator"

const profileFormSchema = z.object({
  shopName: z
    .string()
    .min(2, {
      message: "Shop name must be at least 2 characters.",
    })
    .max(50, {
      message: "Shop name must not be longer than 50 characters.",
    }),
  email: z
    .string({
      required_error: "Please enter a business email.",
    })
    .email(),
  address: z.string().max(160).min(4),
  contact: z.string().min(10, { message: "Contact number must be at least 10 digits."}),
  logoUrl: z.string().optional(),
  loginEmail: z.string().email({ message: "Please enter a valid login email." }),
  loginPassword: z.string().min(6, { message: "Password must be at least 6 characters."}).optional().or(z.literal('')),
})

type ProfileFormValues = z.infer<typeof profileFormSchema>

export function ProfileForm() {
    const [logoPreview, setLogoPreview] = useState<string | null>(null);

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues: {
      shopName: "",
      email: "",
      address: "",
      contact: "",
      logoUrl: "",
      loginEmail: "",
      loginPassword: "",
    },
    mode: "onChange",
  })

  useEffect(() => {
    const shopProfile = getShopProfile();
    const loginCredentials = getLoginCredentials();
    form.reset({
      ...shopProfile,
      loginEmail: loginCredentials.email,
      loginPassword: loginCredentials.password || '',
    });
    if (shopProfile.logoUrl) {
        setLogoPreview(shopProfile.logoUrl);
    }
  }, [form]);

  function onSubmit(data: ProfileFormValues) {
    const profileData: ShopProfile = {
      shopName: data.shopName,
      email: data.email,
      address: data.address,
      contact: data.contact,
      logoUrl: data.logoUrl,
    };
    
    // Only update password if a new one is provided
    const credentialsData: LoginCredentials = {
      email: data.loginEmail,
      ...(data.loginPassword && { password: data.loginPassword }),
    };

    setShopProfile(profileData);
    setLoginCredentials(credentialsData);

    toast({
      title: "Profile updated successfully!",
      description: "Your shop profile and login credentials have been saved.",
    })
    
    // Optional: force a reload to see avatar changes everywhere
    window.dispatchEvent(new Event('storage'));
  }

  const handleLogoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const result = reader.result as string;
        form.setValue('logoUrl', result);
        setLogoPreview(result);
      };
      reader.readAsDataURL(file);
    }
  };


  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <Card>
          <CardHeader>
            <CardTitle>Shop Profile</CardTitle>
            <CardDescription>
              Update your shop's name, address, and contact information.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-8">
            <FormField
              control={form.control}
              name="shopName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Shop Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Your shop's name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Business Email</FormLabel>
                   <FormControl>
                    <Input placeholder="Your shop's public email" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="address"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Address</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Your shop's address"
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="contact"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Contact Number</FormLabel>
                   <FormControl>
                    <Input placeholder="Your shop's contact number" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormItem>
                <FormLabel>Logo</FormLabel>
                 {logoPreview && (
                    <div className="mt-2">
                        <Image src={logoPreview} alt="Logo Preview" width={80} height={80} className="rounded-md object-cover" />
                    </div>
                )}
                <FormControl>
                    <Input type="file" accept="image/png, image/jpeg" onChange={handleLogoChange} />
                </FormControl>
                <FormDescription>
                    Upload a logo for your shop (.png, .jpg).
                </FormDescription>
                <FormMessage />
            </FormItem>
          </CardContent>
        </Card>
        <Card>
            <CardHeader>
                <CardTitle>Security</CardTitle>
                <CardDescription>
                Manage your login credentials.
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-8">
                 <FormField
                    control={form.control}
                    name="loginEmail"
                    render={({ field }) => (
                        <FormItem>
                        <FormLabel>Login Email</FormLabel>
                        <FormControl>
                            <Input placeholder="Enter your login email" {...field} />
                        </FormControl>
                        <FormMessage />
                        </FormItem>
                    )}
                    />
                <FormField
                    control={form.control}
                    name="loginPassword"
                    render={({ field }) => (
                        <FormItem>
                        <FormLabel>New Login Password</FormLabel>
                        <FormControl>
                            <Input type="password" placeholder="Enter new password (leave blank to keep current)" {...field} />
                        </FormControl>
                        <FormDescription>
                            Leave this field blank if you don't want to change the password.
                        </FormDescription>
                        <FormMessage />
                        </FormItem>
                    )}
                />
            </CardContent>
            <CardFooter>
                 <Button type="submit">Update Profile & Security</Button>
            </CardFooter>
        </Card>
      </form>
    </Form>
  )
}
