import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Save, X, ArrowLeft, School, Users, BookOpen, Phone, MapPin, Edit2, Trash2, Camera, Upload } from "lucide-react";
import { toast } from "sonner";

const JENJANG = ["PAUD/TK", "SD", "SMP", "SMA"];
const JENJANG_COLOR = { "PAUD/TK": "bg-pink-100 text-pink-700", "SD": "bg-blue-100 text-blue-700", "SMP": "bg-purple-100 text-purple-700", "SMA": "bg-amber-100 text-amber-700" };

const emptyForm = {
  nama_sekolah: "", jenjang: "SD", npsn: "", alamat: "", kelurahan: "", kecamatan: "",
  kepala_sekolah: "", no_telp: "", jumlah_siswa_total: "", jumlah_siswa_laki: "",
  jumlah_siswa_perempuan: "", jumlah_guru: "", jumlah_rombel: "", jumlah_penerima_mbg: "",
  jadwal_distribusi: "", foto_sekolah_url: "", status: "Aktif"
};

export default function TabSekolah({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [editId, setEditId] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [uploading, setUploading] = useState(false);

  useEffect(() => { load(); }, [sppgId]);

  const load = async () => {
    const data = await api.filter("Sekolah", { sppg_id: sppgId });
    setList(data);
    setLoading(false);
  };

  const handleUploadFoto = async (file) => {
    setUploading(true);
    const { file_url } = await api.upload(file);
    setForm((prev) => ({ ...prev, foto_sekolah_url: file_url }));
    setUploading(false);
    toast.success("Foto terupload");
  };

  const handleSubmit = async () => {
    if (!form.nama_sekolah || !form.jenjang) return toast.error("Nama sekolah dan jenjang wajib diisi");
    const payload = {
      ...form, sppg_id: sppgId,
      jumlah_siswa_total: Number(form.jumlah_siswa_total) || 0,
      jumlah_siswa_laki: Number(form.jumlah_siswa_laki) || 0,
      jumlah_siswa_perempuan: Number(form.jumlah_siswa_perempuan) || 0,
      jumlah_guru: Number(form.jumlah_guru) || 0,
      jumlah_rombel: Number(form.jumlah_rombel) || 0,
      jumlah_penerima_mbg: Number(form.jumlah_penerima_mbg) || 0,
    };
    if (editId) {
      await api.update("Sekolah", editId, payload);
      toast.success("Data sekolah diperbarui");
    } else {
      await api.create("Sekolah", payload);
      toast.success("Sekolah berhasil ditambahkan");
    }
    setShowForm(false); setEditId(null); setForm(emptyForm); load();
  };

  const handleEdit = (s) => {
    setForm({ ...s });
    setEditId(s.id);
    setSelected(null);
    setShowForm(true);
  };

  const handleDelete = async (id) => {
    await api.remove("Sekolah", id);
    toast.success("Sekolah dihapus");
    setSelected(null);
    load();
  };

  // === DETAIL VIEW sekolah ===
  if (selected) {
    const s = selected;
    const pctLaki = s.jumlah_siswa_total > 0 ? Math.round((s.jumlah_siswa_laki / s.jumlah_siswa_total) * 100) : 0;
    const pctPerempuan = 100 - pctLaki;
    return (
      <div className="space-y-5">
        <button onClick={() => setSelected(null)} className="flex items-center gap-2 text-sm text-muted-foreground hover:text-primary">
          <ArrowLeft className="w-4 h-4" /> Kembali ke daftar sekolah
        </button>

        {/* Header sekolah */}
        <div className="bg-card rounded-xl border border-border overflow-hidden">
          {s.foto_sekolah_url ? (
            <img src={s.foto_sekolah_url} alt={s.nama_sekolah} className="w-full h-40 object-cover" />
          ) : (
            <div className="w-full h-32 bg-gradient-to-br from-blue-100 to-blue-200 flex items-center justify-center">
              <School className="w-14 h-14 text-blue-400" />
            </div>
          )}
          <div className="p-5">
            <div className="flex items-start justify-between gap-3 flex-wrap">
              <div>
                <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${JENJANG_COLOR[s.jenjang] || "bg-muted text-muted-foreground"}`}>{s.jenjang}</span>
                <h2 className="text-xl font-black text-foreground mt-1">{s.nama_sekolah}</h2>
                {s.npsn && <p className="text-xs text-muted-foreground">NPSN: {s.npsn}</p>}
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-semibold ${s.status === "Aktif" ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-600"}`}>{s.status}</span>
            </div>

            {/* Info kontak */}
            <div className="mt-4 space-y-2">
              {s.alamat && (
                <div className="flex items-start gap-2 text-sm">
                  <MapPin className="w-4 h-4 text-muted-foreground mt-0.5 flex-shrink-0" />
                  <span className="text-muted-foreground">{s.alamat}{s.kelurahan ? `, Kel. ${s.kelurahan}` : ""}{s.kecamatan ? `, Kec. ${s.kecamatan}` : ""}</span>
                </div>
              )}
              {s.no_telp && (
                <div className="flex items-center gap-2 text-sm">
                  <Phone className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                  <span className="text-muted-foreground">{s.no_telp}</span>
                </div>
              )}
              {s.kepala_sekolah && (
                <div className="flex items-center gap-2 text-sm">
                  <Users className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                  <span>Kepala Sekolah: <span className="font-semibold text-foreground">{s.kepala_sekolah}</span></span>
                </div>
              )}
            </div>

            <div className="flex gap-2 mt-4">
              <Button size="sm" variant="outline" onClick={() => handleEdit(s)}><Edit2 className="w-3.5 h-3.5 mr-1" />Edit</Button>
              <Button size="sm" variant="outline" className="text-destructive border-red-200 hover:bg-red-50" onClick={() => handleDelete(s.id)}><Trash2 className="w-3.5 h-3.5 mr-1" />Hapus</Button>
            </div>
          </div>
        </div>

        {/* Statistik siswa */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="bg-blue-50 rounded-xl border border-blue-200 p-4">
            <p className="text-xs text-blue-600 font-medium">Total Siswa</p>
            <p className="text-2xl font-black text-blue-700">{(s.jumlah_siswa_total || 0).toLocaleString()}</p>
          </div>
          <div className="bg-sky-50 rounded-xl border border-sky-200 p-4">
            <p className="text-xs text-sky-600 font-medium">Laki-laki</p>
            <p className="text-2xl font-black text-sky-700">{(s.jumlah_siswa_laki || 0).toLocaleString()}</p>
            <p className="text-xs text-sky-500">{pctLaki}%</p>
          </div>
          <div className="bg-pink-50 rounded-xl border border-pink-200 p-4">
            <p className="text-xs text-pink-600 font-medium">Perempuan</p>
            <p className="text-2xl font-black text-pink-700">{(s.jumlah_siswa_perempuan || 0).toLocaleString()}</p>
            <p className="text-xs text-pink-500">{pctPerempuan}%</p>
          </div>
          <div className="bg-emerald-50 rounded-xl border border-emerald-200 p-4">
            <p className="text-xs text-emerald-600 font-medium">Penerima MBG</p>
            <p className="text-2xl font-black text-emerald-700">{(s.jumlah_penerima_mbg || 0).toLocaleString()}</p>
          </div>
        </div>

        {/* Bar rasio laki/perempuan */}
        {s.jumlah_siswa_total > 0 && (
          <div className="bg-card rounded-xl border border-border p-4">
            <p className="text-xs font-semibold text-muted-foreground mb-2">Rasio Jenis Kelamin</p>
            <div className="flex rounded-full overflow-hidden h-4">
              <div className="bg-sky-400 transition-all" style={{ width: `${pctLaki}%` }} />
              <div className="bg-pink-400 transition-all flex-1" />
            </div>
            <div className="flex justify-between mt-1.5 text-xs text-muted-foreground">
              <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-sky-400 inline-block" />Laki-laki {pctLaki}%</span>
              <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-pink-400 inline-block" />Perempuan {pctPerempuan}%</span>
            </div>
          </div>
        )}

        {/* Info tambahan */}
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
          {[
            { label: "Jumlah Guru", value: s.jumlah_guru || "-", icon: BookOpen },
            { label: "Rombongan Belajar", value: s.jumlah_rombel ? `${s.jumlah_rombel} rombel` : "-", icon: Users },
            { label: "Jadwal Distribusi", value: s.jadwal_distribusi || "Setiap hari", icon: BookOpen },
          ].map((item) => (
            <div key={item.label} className="bg-card rounded-xl border border-border p-4">
              <p className="text-xs text-muted-foreground">{item.label}</p>
              <p className="text-lg font-bold text-foreground mt-1">{item.value}</p>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Summary */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {JENJANG.map((j) => {
          const sekolahJenjang = list.filter((s) => s.jenjang === j);
          const totalSiswa = sekolahJenjang.reduce((a, s) => a + (s.jumlah_siswa_total || 0), 0);
          return (
            <div key={j} className="bg-card rounded-xl border border-border p-4">
              <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${JENJANG_COLOR[j]}`}>{j}</span>
              <p className="text-xl font-black text-foreground mt-2">{sekolahJenjang.length} <span className="text-sm font-normal text-muted-foreground">sekolah</span></p>
              <p className="text-xs text-muted-foreground">{totalSiswa.toLocaleString()} siswa</p>
            </div>
          );
        })}
      </div>

      <div className="flex justify-between items-center">
        <p className="text-sm text-muted-foreground">{list.length} sekolah terdaftar — klik untuk lihat detail</p>
        <Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm(emptyForm); }}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Sekolah
        </Button>
      </div>

      {/* Form */}
      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold">{editId ? "Edit Sekolah" : "Tambah Sekolah Baru"}</h4>
          {/* Foto */}
          <div>
            <label className="text-xs font-medium mb-2 block">Foto Sekolah</label>
            <label className={`flex items-center gap-3 border-2 border-dashed rounded-xl p-3 cursor-pointer w-fit ${form.foto_sekolah_url ? "border-emerald-400 bg-emerald-50" : "border-border hover:border-primary/50"}`}>
              {form.foto_sekolah_url ? (
                <img src={form.foto_sekolah_url} alt="sekolah" className="w-24 h-16 rounded-xl object-cover" />
              ) : (
                <div className="w-24 h-16 bg-muted rounded-xl flex items-center justify-center gap-2">
                  <Camera className="w-5 h-5 text-muted-foreground" />
                  <span className="text-xs text-muted-foreground">{uploading ? "Upload..." : "Foto"}</span>
                </div>
              )}
              <input type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && handleUploadFoto(e.target.files[0])} />
            </label>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <div><label className="text-xs font-medium mb-1 block">Nama Sekolah *</label><Input value={form.nama_sekolah} onChange={(e) => setForm({ ...form, nama_sekolah: e.target.value })} placeholder="Nama lengkap sekolah" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jenjang *</label>
              <Select value={form.jenjang} onValueChange={(v) => setForm({ ...form, jenjang: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{JENJANG.map((j) => <SelectItem key={j} value={j}>{j}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">Status</label>
              <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent><SelectItem value="Aktif">Aktif</SelectItem><SelectItem value="Tidak Aktif">Tidak Aktif</SelectItem></SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">NPSN</label><Input value={form.npsn} onChange={(e) => setForm({ ...form, npsn: e.target.value })} placeholder="Nomor Pokok Sekolah" /></div>
            <div><label className="text-xs font-medium mb-1 block">Kepala Sekolah</label><Input value={form.kepala_sekolah} onChange={(e) => setForm({ ...form, kepala_sekolah: e.target.value })} placeholder="Nama kepala sekolah" /></div>
            <div><label className="text-xs font-medium mb-1 block">No. Telepon</label><Input value={form.no_telp} onChange={(e) => setForm({ ...form, no_telp: e.target.value })} placeholder="021-xxx" /></div>
            <div><label className="text-xs font-medium mb-1 block">Alamat</label><Input value={form.alamat} onChange={(e) => setForm({ ...form, alamat: e.target.value })} placeholder="Jl. ..." /></div>
            <div><label className="text-xs font-medium mb-1 block">Kelurahan</label><Input value={form.kelurahan} onChange={(e) => setForm({ ...form, kelurahan: e.target.value })} placeholder="Nama kelurahan" /></div>
            <div><label className="text-xs font-medium mb-1 block">Kecamatan</label><Input value={form.kecamatan} onChange={(e) => setForm({ ...form, kecamatan: e.target.value })} placeholder="Nama kecamatan" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jumlah Siswa Total</label><Input type="number" value={form.jumlah_siswa_total} onChange={(e) => setForm({ ...form, jumlah_siswa_total: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Siswa Laki-laki</label><Input type="number" value={form.jumlah_siswa_laki} onChange={(e) => setForm({ ...form, jumlah_siswa_laki: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Siswa Perempuan</label><Input type="number" value={form.jumlah_siswa_perempuan} onChange={(e) => setForm({ ...form, jumlah_siswa_perempuan: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jumlah Guru</label><Input type="number" value={form.jumlah_guru} onChange={(e) => setForm({ ...form, jumlah_guru: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Rombongan Belajar</label><Input type="number" value={form.jumlah_rombel} onChange={(e) => setForm({ ...form, jumlah_rombel: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Penerima MBG</label><Input type="number" value={form.jumlah_penerima_mbg} onChange={(e) => setForm({ ...form, jumlah_penerima_mbg: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jadwal Distribusi</label><Input value={form.jadwal_distribusi} onChange={(e) => setForm({ ...form, jadwal_distribusi: e.target.value })} placeholder="Senin, Rabu, Jumat" /></div>
          </div>
          <div className="flex gap-2">
            <Button size="sm" onClick={handleSubmit}><Save className="w-3.5 h-3.5 mr-1" />Simpan</Button>
            <Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null); }}><X className="w-3.5 h-3.5 mr-1" />Batal</Button>
          </div>
        </div>
      )}

      {/* Grid Sekolah */}
      {loading ? (
        <div className="flex justify-center py-12"><div className="w-6 h-6 border-2 border-primary/20 border-t-primary rounded-full animate-spin" /></div>
      ) : list.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground text-sm">Belum ada data sekolah. Tambahkan sekolah yang terhubung ke SPPG ini.</div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {list.map((s) => (
            <button
              key={s.id}
              onClick={() => setSelected(s)}
              className="bg-card rounded-xl border border-border overflow-hidden hover:shadow-md hover:-translate-y-0.5 transition-all text-left group"
            >
              {s.foto_sekolah_url ? (
                <img src={s.foto_sekolah_url} alt={s.nama_sekolah} className="w-full h-28 object-cover group-hover:opacity-90 transition" />
              ) : (
                <div className="w-full h-28 bg-gradient-to-br from-blue-50 to-blue-100 flex items-center justify-center">
                  <School className="w-10 h-10 text-blue-300" />
                </div>
              )}
              <div className="p-4">
                <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${JENJANG_COLOR[s.jenjang] || "bg-muted text-muted-foreground"}`}>{s.jenjang}</span>
                <h3 className="font-bold text-foreground mt-2 group-hover:text-primary transition-colors text-sm leading-tight">{s.nama_sekolah}</h3>
                {s.kepala_sekolah && <p className="text-xs text-muted-foreground mt-1">KS: {s.kepala_sekolah}</p>}
                <div className="flex items-center gap-3 mt-2">
                  <span className="text-xs font-semibold text-blue-600">{(s.jumlah_siswa_total || 0).toLocaleString()} siswa</span>
                  <span className="text-xs text-muted-foreground">{(s.jumlah_penerima_mbg || 0).toLocaleString()} MBG</span>
                </div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}