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, Trash2, Edit2, Save, X, Truck, Upload } from "lucide-react";
import { toast } from "sonner";

const JENIS = ["Siswa SD", "Siswa SMP", "PAUD/TK", "Ibu Hamil", "Ibu Menyusui"];
const emptyForm = { tanggal: new Date().toISOString().slice(0, 10), nama_sekolah: "", jenis_penerima: "", jumlah_omprengan: "", nama_supir: "", waktu_berangkat: "", waktu_tiba: "", kondisi: "Baik", catatan: "", foto_url: "" };

export default function TabOmprengan({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  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("DataOmprengan", { sppg_id: sppgId });
    setList(data);
    setLoading(false);
  };

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

  const handleSubmit = async () => {
    if (!form.nama_sekolah || !form.jenis_penerima) return toast.error("Nama sekolah dan jenis penerima wajib diisi");
    const payload = { ...form, sppg_id: sppgId, jumlah_omprengan: Number(form.jumlah_omprengan) };
    if (editId) { await api.update("DataOmprengan", editId, payload); toast.success("Diperbarui"); }
    else { await api.create("DataOmprengan", payload); toast.success("Data distribusi ditambahkan"); }
    setShowForm(false); setEditId(null); setForm(emptyForm); load();
  };

  const handleEdit = (d) => { setForm({ ...d }); setEditId(d.id); setShowForm(true); };
  const handleDelete = async (id) => { await api.remove("DataOmprengan", id); toast.success("Dihapus"); load(); };

  const totalOmprengan = list.reduce((a, d) => a + (d.jumlah_omprengan || 0), 0);
  const byJenis = JENIS.map((j) => ({ jenis: j, total: list.filter((d) => d.jenis_penerima === j).reduce((a, d) => a + (d.jumlah_omprengan || 0), 0) }));

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
        <div className="bg-primary/5 rounded-xl border border-primary/20 p-3 col-span-2 sm:col-span-1">
          <p className="text-xs text-muted-foreground">Total Omprengan</p>
          <p className="text-2xl font-black text-primary">{totalOmprengan.toLocaleString()}</p>
        </div>
        {byJenis.map((j) => (
          <div key={j.jenis} className="bg-card rounded-xl border border-border p-3">
            <p className="text-xs text-muted-foreground">{j.jenis}</p>
            <p className="text-lg font-black text-foreground">{j.total.toLocaleString()}</p>
          </div>
        ))}
      </div>

      <div className="flex justify-end">
        <Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm(emptyForm); }}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Data Distribusi
        </Button>
      </div>

      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold">{editId ? "Edit Data" : "Tambah Data Distribusi Omprengan"}</h4>
          <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">Tanggal</label><Input type="date" value={form.tanggal} onChange={(e) => setForm({ ...form, tanggal: e.target.value })} /></div>
            <div><label className="text-xs font-medium mb-1 block">Nama Sekolah / Lokasi *</label><Input value={form.nama_sekolah} onChange={(e) => setForm({ ...form, nama_sekolah: e.target.value })} placeholder="Nama sekolah" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jenis Penerima *</label>
              <Select value={form.jenis_penerima} onValueChange={(v) => setForm({ ...form, jenis_penerima: v })}>
                <SelectTrigger><SelectValue placeholder="Pilih jenis" /></SelectTrigger>
                <SelectContent>{JENIS.map((j) => <SelectItem key={j} value={j}>{j}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">Jumlah Omprengan</label><Input type="number" value={form.jumlah_omprengan} onChange={(e) => setForm({ ...form, jumlah_omprengan: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Nama Supir</label><Input value={form.nama_supir} onChange={(e) => setForm({ ...form, nama_supir: e.target.value })} placeholder="Nama supir" /></div>
            <div><label className="text-xs font-medium mb-1 block">Kondisi</label>
              <Select value={form.kondisi} onValueChange={(v) => setForm({ ...form, kondisi: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent><SelectItem value="Baik">Baik</SelectItem><SelectItem value="Ada Kendala">Ada Kendala</SelectItem></SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">Waktu Berangkat</label><Input type="time" value={form.waktu_berangkat} onChange={(e) => setForm({ ...form, waktu_berangkat: e.target.value })} /></div>
            <div><label className="text-xs font-medium mb-1 block">Waktu Tiba</label><Input type="time" value={form.waktu_tiba} onChange={(e) => setForm({ ...form, waktu_tiba: e.target.value })} /></div>
            <div><label className="text-xs font-medium mb-1 block">Catatan</label><Input value={form.catatan} onChange={(e) => setForm({ ...form, catatan: e.target.value })} placeholder="Catatan distribusi" /></div>
          </div>
          <div>
            <label className="text-xs font-medium mb-2 block">Foto Distribusi</label>
            <label className={`flex items-center gap-3 border-2 border-dashed rounded-xl p-3 cursor-pointer ${form.foto_url ? "border-emerald-400 bg-emerald-50" : "border-border hover:border-primary/50"}`}>
              {form.foto_url ? <img src={form.foto_url} alt="foto" className="w-16 h-16 rounded-lg object-cover" /> : <><Upload className="w-5 h-5 text-muted-foreground" /><span className="text-sm text-muted-foreground">{uploading ? "Mengupload..." : "Upload foto distribusi"}</span></>}
              <input type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0])} />
            </label>
          </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>
      )}

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        {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-sm text-muted-foreground">Belum ada data distribusi omprengan.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>{["Tanggal", "Sekolah/Lokasi", "Jenis Penerima", "Jumlah", "Supir", "Waktu", "Kondisi", "Foto", "Aksi"].map((h) => (
                  <th key={h} className="text-left px-3 py-3 text-xs font-semibold text-muted-foreground">{h}</th>
                ))}</tr>
              </thead>
              <tbody className="divide-y divide-border">
                {list.map((d) => (
                  <tr key={d.id} className="hover:bg-muted/30">
                    <td className="px-3 py-3 text-muted-foreground">{d.tanggal}</td>
                    <td className="px-3 py-3 font-medium">{d.nama_sekolah}</td>
                    <td className="px-3 py-3"><span className="px-2 py-0.5 rounded-full text-xs bg-blue-100 text-blue-700">{d.jenis_penerima}</span></td>
                    <td className="px-3 py-3 font-bold text-primary">{(d.jumlah_omprengan || 0).toLocaleString()}</td>
                    <td className="px-3 py-3 text-muted-foreground">{d.nama_supir || "-"}</td>
                    <td className="px-3 py-3 text-muted-foreground text-xs">{d.waktu_berangkat && d.waktu_tiba ? `${d.waktu_berangkat} - ${d.waktu_tiba}` : "-"}</td>
                    <td className="px-3 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${d.kondisi === "Baik" ? "bg-emerald-100 text-emerald-700" : "bg-red-100 text-red-700"}`}>{d.kondisi}</span></td>
                    <td className="px-3 py-3">{d.foto_url ? <a href={d.foto_url} target="_blank" rel="noreferrer" className="text-xs text-primary hover:underline">Lihat</a> : "-"}</td>
                    <td className="px-3 py-3">
                      <div className="flex gap-1">
                        <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleEdit(d)}><Edit2 className="w-3.5 h-3.5" /></Button>
                        <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => handleDelete(d.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}