import { useState } from "react";
import { api } from "@/services/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Edit2, Save, X, MapPin, Building2, Users, Baby, Heart } from "lucide-react";
import { toast } from "sonner";

const formatRp = (n) => `Rp ${(n || 0).toLocaleString("id-ID")}`;

export default function TabInfoSPPG({ sppg, onUpdate }) {
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState({ ...sppg });
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    const updated = await api.update("SPPG", sppg.id, form);
    onUpdate(updated);
    setEditing(false);
    setSaving(false);
    toast.success("Data SPPG berhasil diperbarui");
  };

  const Field = ({ label, field, type = "text" }) => (
    <div>
      <label className="text-xs font-medium text-muted-foreground block mb-1">{label}</label>
      {editing ? (
        <Input
          type={type}
          value={form[field] || ""}
          onChange={(e) => setForm({ ...form, [field]: type === "number" ? Number(e.target.value) : e.target.value })}
        />
      ) : (
        <p className="text-sm font-semibold text-foreground">{type === "number" ? formatRp(sppg[field]) : (sppg[field] || "-")}</p>
      )}
    </div>
  );

  let sekolahList = [];
  try { sekolahList = JSON.parse(sppg.detail_sekolah || "[]"); } catch {}

  return (
    <div className="space-y-6">
      <div className="bg-card rounded-xl border border-border p-5">
        <div className="flex items-center justify-between mb-5">
          <h3 className="font-bold text-foreground flex items-center gap-2">
            <Building2 className="w-4 h-4 text-primary" />Profil SPPG
          </h3>
          {editing ? (
            <div className="flex gap-2">
              <Button size="sm" onClick={handleSave} disabled={saving}><Save className="w-3.5 h-3.5 mr-1" />Simpan</Button>
              <Button size="sm" variant="outline" onClick={() => { setEditing(false); setForm({ ...sppg }); }}><X className="w-3.5 h-3.5 mr-1" />Batal</Button>
            </div>
          ) : (
            <Button size="sm" variant="outline" onClick={() => setEditing(true)}><Edit2 className="w-3.5 h-3.5 mr-1" />Edit</Button>
          )}
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          <Field label="Nama SPPG" field="nama" />
          <Field label="Alamat Lengkap" field="alamat_lengkap" />
          <Field label="Lokasi / Kelurahan" field="lokasi" />
          <Field label="Kabupaten" field="kabupaten" />
          <Field label="Provinsi" field="provinsi" />
          <Field label="Status" field="status" />
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground flex items-center gap-2 mb-5">
          <Users className="w-4 h-4 text-primary" />Dana dan Penerima
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          <Field label="Dana Pemerintah per Bulan" field="dana_pemerintah_perbulan" type="number" />
          <Field label="Dana Diterima" field="dana_diterima" type="number" />
          <Field label="Dana Dibelanjakan" field="dana_dibelanjakan" type="number" />
          <Field label="Sisa Dana" field="sisa_dana" type="number" />
          <Field label="Jumlah Sekolah" field="jumlah_sekolah" type="number" />
          <Field label="Total Jumlah Siswa" field="jumlah_siswa" type="number" />
          <Field label="Jumlah Omprengan" field="jumlah_omprengan" type="number" />
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground flex items-center gap-2 mb-5">
          <Heart className="w-4 h-4 text-primary" />Ibu Hamil dan Menyusui
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div className="bg-pink-50 rounded-xl p-4 flex items-center gap-4">
            <div className="w-12 h-12 bg-pink-100 rounded-full flex items-center justify-center">
              <Heart className="w-6 h-6 text-pink-500" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Ibu Hamil</p>
              {editing ? (
                <Input type="number" className="mt-1 w-28" value={form.jumlah_ibu_hamil || ""} onChange={(e) => setForm({ ...form, jumlah_ibu_hamil: Number(e.target.value) })} />
              ) : (
                <p className="text-2xl font-black text-pink-600">{sppg.jumlah_ibu_hamil || 0} orang</p>
              )}
            </div>
          </div>
          <div className="bg-purple-50 rounded-xl p-4 flex items-center gap-4">
            <div className="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
              <Baby className="w-6 h-6 text-purple-500" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">Ibu Menyusui</p>
              {editing ? (
                <Input type="number" className="mt-1 w-28" value={form.jumlah_ibu_menyusui || ""} onChange={(e) => setForm({ ...form, jumlah_ibu_menyusui: Number(e.target.value) })} />
              ) : (
                <p className="text-2xl font-black text-purple-600">{sppg.jumlah_ibu_menyusui || 0} orang</p>
              )}
            </div>
          </div>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground flex items-center gap-2 mb-4">
          <MapPin className="w-4 h-4 text-primary" />Detail Sekolah dan Jumlah Anak
        </h3>
        {sekolahList.length === 0 ? (
          <p className="text-sm text-muted-foreground">Belum ada data sekolah. Tambahkan array JSON di field detail_sekolah pada SPPG, contoh: [{"{"}"nama":"SDN 1","jenis":"SD","jumlah":120{"}"}]</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  <th className="text-left px-3 py-2 text-xs font-semibold text-muted-foreground">Nama Sekolah</th>
                  <th className="text-left px-3 py-2 text-xs font-semibold text-muted-foreground">Jenis</th>
                  <th className="text-right px-3 py-2 text-xs font-semibold text-muted-foreground">Jumlah Anak</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {sekolahList.map((s, i) => (
                  <tr key={i} className="hover:bg-muted/30">
                    <td className="px-3 py-2 font-medium">{s.nama}</td>
                    <td className="px-3 py-2 text-muted-foreground">{s.jenis}</td>
                    <td className="px-3 py-2 text-right font-semibold">{s.jumlah}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}