"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { updateSiteSettings } from "@/app/(dashboard)/dashboard/settings/actions"

const settingsSchema = z.object({
    site_title: z.string().min(2, "Site başlığı en az 2 karakter olmalıdır."),
    site_description: z.string().default(""),
    contact_email: z.union([z.literal(""), z.string().email("Geçerli bir e-posta adresi giriniz.")]).default(""),
    contact_phone: z.string().default(""),
    currency: z.string().default("TRY"),
})

type SettingsFormValues = z.infer<typeof settingsSchema>

interface SiteSettingsFormProps {
    initialData: any
}

export function SiteSettingsForm({ initialData }: SiteSettingsFormProps) {
    const router = useRouter()
    const [loading, setLoading] = useState(false)

    const form = useForm<SettingsFormValues>({
        resolver: zodResolver(settingsSchema),
        defaultValues: {
            site_title: initialData?.site_title || "ParaKasa",
            site_description: initialData?.site_description || "",
            contact_email: initialData?.contact_email || "",
            contact_phone: initialData?.contact_phone || "",
            currency: initialData?.currency || "TRY",
        },
    })

    const onSubmit = async (data: SettingsFormValues) => {
        setLoading(true)
        try {
            // @ts-ignore
            const result = await updateSiteSettings(data)

            if (result.error) {
                toast.error(result.error)
                return
            }

            toast.success("Site ayarları güncellendi.")
            router.refresh()
        } catch (error) {
            toast.error("Bir sorun oluştu.")
        } finally {
            setLoading(false)
        }
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle>Genel Ayarlar</CardTitle>
                <CardDescription>Web sitesinin genel yapılandırma ayarları.</CardDescription>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="site_title"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Site Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="ParaKasa" {...field} />
                                    </FormControl>
                                    <FormDescription>Tarayıcı sekmesinde görünen ad.</FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="site_description"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Site Açıklaması</FormLabel>
                                    <FormControl>
                                        <Textarea placeholder="Premium çelik kasalar..." {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="contact_email"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>İletişim E-posta</FormLabel>
                                        <FormControl>
                                            <Input placeholder="info@parakasa.com" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="contact_phone"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>İletişim Telefon</FormLabel>
                                        <FormControl>
                                            <Input placeholder="+90 555 123 45 67" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="currency"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Para Birimi</FormLabel>
                                    <FormControl>
                                        <Input placeholder="TRY" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <Button type="submit" disabled={loading}>
                            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Ayarları Kaydet
                        </Button>
                    </form>
                </Form>
            </CardContent>
        </Card>
    )
}
