'use client';

import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { ProfilSchema } from '@/lib/validations';
import { upsertProfil } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";

type ProfilFormValues = z.infer<typeof ProfilSchema>;

export default function ProfilForm({ initialData }: { initialData?: any }) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [organigramFile, setOrganigramFile] = useState<File | null>(null);

    const form = useForm<ProfilFormValues>({
        resolver: zodResolver(ProfilSchema),
        defaultValues: initialData || {
            sejarah_p1: '',
            sejarah_p2: '',
            sejarah_card1: '',
            sejarah_card2: '',
            lambang_desc: '',
            lambang_tulisan: '',
            lambang_mahkota: '',
            lambang_lingkaran: '',
            lambang_sayap: '',
            lambang_elektron: '',
            lambang_segitiga: '',
            warna_biru: '',
            warna_merah: '',
            warna_putih: '',
            mars_ciptaan: '',
            mars_lirik: '',
            hymne_ciptaan: '',
            hymne_lirik: '',
            organigramDpmUrl: '',
        },
    });

    const watchOrganigramUrl = organigramFile ? URL.createObjectURL(organigramFile) : form.watch('organigramDpmUrl');

    const onSubmit = async (values: ProfilFormValues) => {
        setIsSubmitting(true);
        try {
            let organigramDpmUrl = values.organigramDpmUrl || '';
            if (organigramFile) organigramDpmUrl = await uploadImage(organigramFile);

            const payload = { ...values, organigramDpmUrl };
            const result = await upsertProfil(payload);
            if (result.success) {
                toast.success(result.message);
                setOrganigramFile(null);
            } else {
                toast.error(result.message);
            }
        } catch (e: any) {
            toast.error('Gagal menyimpan data profil', { description: e.message });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 bg-white p-8 rounded-3xl border border-slate-200 shadow-sm">
            <Tabs defaultValue="sejarah" className="w-full">
                <TabsList className="grid w-full grid-cols-1 md:grid-cols-3 mb-8 h-auto p-1 bg-slate-100/50 rounded-2xl">
                    <TabsTrigger value="sejarah" className="rounded-xl py-3 data-[state=active]:bg-white data-[state=active]:shadow-sm">Sejarah Himpunan</TabsTrigger>
                    <TabsTrigger value="lambang" className="rounded-xl py-3 data-[state=active]:bg-white data-[state=active]:shadow-sm">Makna Lambang</TabsTrigger>
                    <TabsTrigger value="lagu" className="rounded-xl py-3 data-[state=active]:bg-white data-[state=active]:shadow-sm">Mars & Hymne</TabsTrigger>
                </TabsList>

                {/* TAB SEJARAH */}
                <TabsContent value="sejarah" className="space-y-6 mt-0">
                    <div>
                        <h3 className="text-lg font-bold text-slate-800">Sejarah Himpunan</h3>
                        <p className="text-sm text-slate-500 mb-6">Paragraf-paragraf sejarah yang tampil di tab "Sejarah Singkat".</p>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-4 border rounded-2xl p-6 bg-slate-50/50">
                            <h4 className="font-semibold text-slate-700 flex items-center gap-2">📝 Bagian Teks Utama</h4>
                            <div className="space-y-2">
                                <Label>Sejarah Paragraf 1</Label>
                                <Textarea rows={5} {...form.register('sejarah_p1')} className="bg-white" />
                                {form.formState.errors.sejarah_p1 && <p className="text-sm text-red-500">{form.formState.errors.sejarah_p1.message}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label>Sejarah Paragraf 2 (Momentum Pendirian)</Label>
                                <Textarea rows={6} {...form.register('sejarah_p2')} className="bg-white" />
                                {form.formState.errors.sejarah_p2 && <p className="text-sm text-red-500">{form.formState.errors.sejarah_p2.message}</p>}
                            </div>
                        </div>

                        <div className="space-y-4 border rounded-2xl p-6 bg-blue-50/30">
                            <h4 className="font-semibold text-slate-700 flex items-center gap-2">💡 Info Cards</h4>
                            <div className="space-y-2">
                                <Label>Card Kanan Atas (Evolusi Nama)</Label>
                                <Textarea rows={4} {...form.register('sejarah_card1')} className="bg-white" />
                                {form.formState.errors.sejarah_card1 && <p className="text-sm text-red-500">{form.formState.errors.sejarah_card1.message}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label>Card Kanan Bawah (Kondisi Terkini)</Label>
                                <Textarea rows={4} {...form.register('sejarah_card2')} className="bg-white" />
                                {form.formState.errors.sejarah_card2 && <p className="text-sm text-red-500">{form.formState.errors.sejarah_card2.message}</p>}
                            </div>
                        </div>
                    </div>
                </TabsContent>

                {/* TAB LAMBANG */}
                <TabsContent value="lambang" className="space-y-6 mt-0">
                    <div>
                        <h3 className="text-lg font-bold text-slate-800">Makna Lambang</h3>
                        <p className="text-sm text-slate-500 mb-6">Deskripsi elemen-elemen bentuk dan warna dari logo HMF.</p>
                    </div>
                    
                    <div className="space-y-2 max-w-3xl">
                        <Label>Deskripsi Pembuka Lambang</Label>
                        <Textarea rows={3} {...form.register('lambang_desc')} />
                        {form.formState.errors.lambang_desc && <p className="text-sm text-red-500">{form.formState.errors.lambang_desc.message}</p>}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 pt-6">
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Tulisan & Lingkaran</Label>
                            <Textarea rows={3} {...form.register('lambang_tulisan')} className="bg-white" />
                        </div>
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Mahkota Segilima</Label>
                            <Textarea rows={3} {...form.register('lambang_mahkota')} className="bg-white" />
                        </div>
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Lingkaran Biru Dalam</Label>
                            <Textarea rows={3} {...form.register('lambang_lingkaran')} className="bg-white" />
                        </div>
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Sepasang Sayap</Label>
                            <Textarea rows={3} {...form.register('lambang_sayap')} className="bg-white" />
                        </div>
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Lintasan Elektron Merah</Label>
                            <Textarea rows={3} {...form.register('lambang_elektron')} className="bg-white" />
                        </div>
                        <div className="space-y-2 border rounded-xl p-4 bg-slate-50/50">
                            <Label className="text-blue-600 font-bold">Segitiga Terbalik Merah</Label>
                            <Textarea rows={3} {...form.register('lambang_segitiga')} className="bg-white" />
                        </div>
                    </div>

                    <div className="pt-8 mt-8 border-t border-slate-100">
                        <h4 className="font-bold text-slate-700 mb-4">Simbolik Warna</h4>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                            <div className="space-y-2 border-l-4 border-blue-500 pl-4">
                                <Label>Warna Biru</Label>
                                <Textarea rows={3} {...form.register('warna_biru')} />
                            </div>
                            <div className="space-y-2 border-l-4 border-red-500 pl-4">
                                <Label>Warna Merah</Label>
                                <Textarea rows={3} {...form.register('warna_merah')} />
                            </div>
                            <div className="space-y-2 border-l-4 border-slate-200 pl-4">
                                <Label>Warna Putih</Label>
                                <Textarea rows={3} {...form.register('warna_putih')} />
                            </div>
                        </div>
                    </div>
                </TabsContent>

                {/* TAB LAGU */}
                <TabsContent value="lagu" className="space-y-6 mt-0">
                    <div>
                        <h3 className="text-lg font-bold text-slate-800">Mars & Hymne</h3>
                        <p className="text-sm text-slate-500 mb-6">Lirik dan detail Mars serta Hymne HMF FPMIPA UPI.</p>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        {/* Mars */}
                        <div className="space-y-5 border rounded-2xl p-6 bg-red-50/30">
                            <div className="flex items-center gap-3 mb-2">
                                <div className="w-10 h-10 bg-red-100 text-red-600 flex items-center justify-center rounded-xl font-bold text-xl">🎵</div>
                                <h3 className="font-bold text-xl text-red-900">MARS HMF</h3>
                            </div>
                            <div className="space-y-2">
                                <Label>Nama Pencipta</Label>
                                <Input {...form.register('mars_ciptaan')} className="bg-white" />
                            </div>
                            <div className="space-y-2">
                                <Label>Lirik Lengkap</Label>
                                <Textarea rows={14} {...form.register('mars_lirik')} placeholder="Gunakan Enter/Baris baru untuk memisahkan lirik" className="bg-white" />
                            </div>
                        </div>

                        {/* Hymne */}
                        <div className="space-y-5 border rounded-2xl p-6 bg-blue-50/30">
                            <div className="flex items-center gap-3 mb-2">
                                <div className="w-10 h-10 bg-blue-100 text-blue-600 flex items-center justify-center rounded-xl font-bold text-xl">🎼</div>
                                <h3 className="font-bold text-xl text-blue-900">HYMNE HMF</h3>
                            </div>
                            <div className="space-y-2">
                                <Label>Nama Pencipta</Label>
                                <Input {...form.register('hymne_ciptaan')} className="bg-white" />
                            </div>
                            <div className="space-y-2">
                                <Label>Lirik Lengkap</Label>
                                <Textarea rows={14} {...form.register('hymne_lirik')} placeholder="Gunakan Enter/Baris baru untuk memisahkan lirik" className="bg-white" />
                            </div>
                        </div>
                    </div>
                </TabsContent>
            </Tabs>

            <div className="pt-6 mt-6 border-t flex justify-end">
                <Button type="submit" size="lg" className="w-full md:w-auto px-10 rounded-xl" disabled={isSubmitting}>
                    {isSubmitting ? 'Menyimpan...' : 'Simpan Perubahan Profil'}
                </Button>
            </div>
        </form>
    );
}
