"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import { Loader2, UserCog } from "lucide-react";

interface SiswaProfile {
  id: string;
  nisn: string;
  nis: string;
  nama: string;
  kelas?: string;
  rombel?: { namaRombel: string };
  jurusan?: { namaJurusan: string };
  agama: string;
  noWa?: string;
  noWaOrtu?: string;
  tingkat: string;
  // New Fields
  tempatLahir?: string;
  tanggalLahir?: string;
  alamat?: string;
  desa?: string;
  kecamatan?: string;
  kabupaten?: string;
  namaAyah?: string;
  pekerjaanAyah?: string;
  namaIbu?: string;
  pekerjaanIbu?: string;
}

const SiswaProfileSchema = z.object({
  nama: z.string().min(1, "Nama tidak boleh kosong"),
  agama: z.string().min(1, "Agama tidak boleh kosong"),
  noWa: z.string().optional(),
  noWaOrtu: z.string().optional(),
  // New Fields
  tempatLahir: z.string().optional(),
  tanggalLahir: z.string().optional(),
  alamat: z.string().optional(),
  desa: z.string().optional(),
  kecamatan: z.string().optional(),
  kabupaten: z.string().optional(),
  namaAyah: z.string().optional(),
  pekerjaanAyah: z.string().optional(),
  namaIbu: z.string().optional(),
  pekerjaanIbu: z.string().optional(),
});

type SiswaProfileData = z.infer<typeof SiswaProfileSchema>;

export function SiswaProfileForm() {
  const [loading, setLoading] = useState(true);
  const [profile, setProfile] = useState<SiswaProfile | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<SiswaProfileData>({
    resolver: zodResolver(SiswaProfileSchema),
  });

  useEffect(() => {
    fetchProfile();
  }, []);

  const fetchProfile = async () => {
    try {
      const res = await fetch("/api/me/siswa");
      const data = await res.json();
      if (data.success) {
        setProfile(data.data);
        setValue("nama", data.data.nama);
        setValue("agama", data.data.agama);
        setValue("noWa", data.data.noWa || "");
        setValue("noWaOrtu", data.data.noWaOrtu || "");
        // New Fields
        setValue("tempatLahir", data.data.tempatLahir || "");
        setValue(
          "tanggalLahir",
          data.data.tanggalLahir ? new Date(data.data.tanggalLahir).toISOString().split("T")[0] : "",
        );
        setValue("alamat", data.data.alamat || "");
        setValue("desa", data.data.desa || "");
        setValue("kecamatan", data.data.kecamatan || "");
        setValue("kabupaten", data.data.kabupaten || "");
        setValue("namaAyah", data.data.namaAyah || "");
        setValue("pekerjaanAyah", data.data.pekerjaanAyah || "");
        setValue("namaIbu", data.data.namaIbu || "");
        setValue("pekerjaanIbu", data.data.pekerjaanIbu || "");
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const onSubmit = async (data: SiswaProfileData) => {
    setIsSubmitting(true);
    try {
      const res = await fetch("/api/me/siswa", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.message || "Gagal update profil");

      toast.success("Profil berhasil diperbarui");
      fetchProfile(); // Refresh
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Terjadi kesalahan");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) return <div className="text-muted-foreground py-4 text-center">Memuat data siswa...</div>;
  if (!profile) return null;

  return (
    <Card className="md:col-span-3">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <UserCog className="h-5 w-5" />
          Data Siswa
        </CardTitle>
        <CardDescription>
          Informasi detail data siswa Anda. Beberapa data hanya dapat diubah oleh Admin.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="grid gap-6 md:grid-cols-2">
          {/* Read Only Fields */}
          <div className="space-y-2">
            <Label className="text-muted-foreground">NISN</Label>
            <Input value={profile.nisn} disabled className="bg-muted" />
          </div>
          <div className="space-y-2">
            <Label className="text-muted-foreground">NIS</Label>
            <Input value={profile.nis} disabled className="bg-muted" />
          </div>
          <div className="space-y-2">
            <Label className="text-muted-foreground">Kelas</Label>
            <Input value={profile.rombel?.namaRombel || profile.kelas || "-"} disabled className="bg-muted" />
          </div>
          <div className="space-y-2">
            <Label className="text-muted-foreground">Jurusan</Label>
            <Input value={profile.jurusan?.namaJurusan || "-"} disabled className="bg-muted" />
          </div>

          {/* Editable Fields */}
          <div className="col-span-2 my-2 border-t"></div>

          <div className="space-y-2 md:col-span-2">
            <Label htmlFor="nama">Nama Lengkap</Label>
            <Input id="nama" {...register("nama")} />
            {errors.nama && <p className="text-destructive text-sm">{errors.nama.message}</p>}
          </div>

          <div className="space-y-2">
            <Label htmlFor="tempatLahir">Tempat Lahir</Label>
            <Input id="tempatLahir" {...register("tempatLahir")} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="tanggalLahir">Tanggal Lahir</Label>
            <Input id="tanggalLahir" type="date" {...register("tanggalLahir")} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="alamat">Alamat</Label>
            <Input id="alamat" {...register("alamat")} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="desa">Desa</Label>
            <Input id="desa" {...register("desa")} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="kecamatan">Kecamatan</Label>
            <Input id="kecamatan" {...register("kecamatan")} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="kabupaten">Kabupaten</Label>
            <Input id="kabupaten" {...register("kabupaten")} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="noWa">No. WhatsApp</Label>
            <Input id="noWa" {...register("noWa")} placeholder="08..." />
            {errors.noWa && <p className="text-destructive text-sm">{errors.noWa.message}</p>}
          </div>

          <div className="space-y-2">
            <Label htmlFor="agama">Agama</Label>
            <Input id="agama" {...register("agama")} />
            {errors.agama && <p className="text-destructive text-sm">{errors.agama.message}</p>}
          </div>

          <div className="space-y-2">
            <Label htmlFor="namaAyah">Nama Ayah</Label>
            <Input id="namaAyah" {...register("namaAyah")} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="pekerjaanAyah">Pekerjaan Ayah</Label>
            <Input id="pekerjaanAyah" {...register("pekerjaanAyah")} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="namaIbu">Nama Ibu</Label>
            <Input id="namaIbu" {...register("namaIbu")} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="pekerjaanIbu">Pekerjaan Ibu</Label>
            <Input id="pekerjaanIbu" {...register("pekerjaanIbu")} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="noWaOrtu">No. WhatsApp Orang Tua</Label>
            <Input id="noWaOrtu" {...register("noWaOrtu")} placeholder="08..." />
            {errors.noWaOrtu && <p className="text-destructive text-sm">{errors.noWaOrtu.message}</p>}
          </div>

          <div className="mt-4 flex justify-end md:col-span-2">
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Simpan Perubahan
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
