"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
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 { Textarea } from "@/components/ui/textarea"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"

const productSchema = z.object({
    name: z.string().min(2, "Ürün adı en az 2 karakter olmalıdır"),
    category: z.string().min(1, "Kategori seçiniz"),
    description: z.string().optional(),
    price: z.coerce.number().min(0, "Fiyat 0'dan küçük olamaz"),
    image_url: z.string().optional(),
})

type ProductFormValues = z.infer<typeof productSchema>

import { createProduct, updateProduct } from "@/app/(dashboard)/dashboard/products/actions"

// Define the shape of data coming from Supabase
interface Product {
    id: number
    name: string
    category: string
    description: string | null
    price: number
    image_url: string | null
    created_at: string
}

interface ProductFormProps {
    initialData?: Product
}

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

    const form = useForm<ProductFormValues>({
        resolver: zodResolver(productSchema) as any,
        defaultValues: initialData ? {
            name: initialData.name,
            category: initialData.category,
            description: initialData.description || "",
            price: initialData.price,
            image_url: initialData.image_url || "",
        } : {
            name: "",
            category: "",
            description: "",
            price: 0,
            image_url: "",
        },
    })

    async function onSubmit(data: ProductFormValues) {
        try {
            setLoading(true)

            let result
            if (initialData) {
                result = await updateProduct(initialData.id, data)
            } else {
                result = await createProduct(data)
            }

            if (!result.success) {
                toast.error(result.error || "Bir hata oluştu")
                return
            }

            toast.success(initialData ? "Ürün güncellendi" : "Ürün başarıyla oluşturuldu")
            router.push("/dashboard/products")
            router.refresh()
        } catch {
            toast.error("Bir aksilik oldu")
        } finally {
            setLoading(false)
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 w-full max-w-2xl">
                <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Ürün Adı</FormLabel>
                            <FormControl>
                                <Input placeholder="Çelik Kasa Model X" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="category"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Kategori</FormLabel>
                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                    <FormControl>
                                        <SelectTrigger>
                                            <SelectValue placeholder="Kategori seçin" />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        <SelectItem value="ev">Ev Tipi</SelectItem>
                                        <SelectItem value="ofis">Ofis Tipi</SelectItem>
                                        <SelectItem value="otel">Otel Kasası</SelectItem>
                                        <SelectItem value="ozel">Özel Üretim</SelectItem>
                                        <SelectItem value="diger">Diğer</SelectItem>
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="price"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Fiyat (₺)</FormLabel>
                                <FormControl>
                                    <Input type="number" placeholder="0.00" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <FormField
                    control={form.control}
                    name="image_url"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Görsel URL (Opsiyonel)</FormLabel>
                            <FormControl>
                                <Input placeholder="https://..." {...field} />
                            </FormControl>
                            <FormDescription>
                                Ürün görseli için şimdilik dış bağlantı kullanın.
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Açıklama</FormLabel>
                            <FormControl>
                                <Textarea placeholder="Ürün özellikleri..." {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <Button type="submit" disabled={loading}>
                    {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    {initialData ? "Güncelle" : "Oluştur"}
                </Button>
            </form>
        </Form>
    )
}
