import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Save, X, Upload, FileText, CheckCircle } from "lucide-react";
import { toast } from "sonner";

const STATUS_COLORS = {
  Draft: "bg-gray-100 text-gray-600",
  Dikirim: "bg-blue-100 text-blue-700",
  Divalidasi: "bg-emerald-100 text-emerald-700",
  Ditolak: "bg-red-100 text-red-700",
};

const emptyForm = {
  tanggal: new Date().toISOString().slice(0, 10),
  jenis: "Harian",
  menu_pagi: "",
  menu_siang: "",
  jumlah_omprengan: "",
  jumlah_terdistribusi: "",
  operasional_dapur: "",
  biaya_operasional: "",
  kendala: "",
  catatan: "",
  foto_distribusi_url: "",
  foto_makanan_url: "",
  status: "Draft",
};

export default function TabLaporan({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [filterJenis, setFilterJenis] = useState("Semua");
  const [uploading, setUploading] = useState({ distribusi: false, makanan: false });

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

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

  const handleUpload = async (field, file) => {
    setUploading((prev) => ({ ...prev, [field]: true }));
    const { file_url } = await api.upload(file);
    setForm((prev) => ({ ...prev, [field === "distribusi" ? "foto_distribusi_url" : "foto_makanan_url"]: file_url }));
    setUploading((prev) => ({ ...prev, [field]: false }));
    toast.success("Foto terupload");
  };

  const handleSubmit = async () => {
    if (!form.tanggal || !form.jenis) return toast.error("Tanggal dan jenis laporan wajib diisi");
    const payload = {
      ...form,
      sppg_id: sppgId,
      jumlah_omprengan: Number(form.jumlah_omprengan),
      jumlah_terdistribusi: Number(form.jumlah_terdistribusi),
      biaya_operasional: Number(form.biaya_operasional),
    };
    await api.create("LaporanHarian", payload);
    toast.success("Laporan berhasil disimpan");
    setShowForm(false);
    setForm(emptyForm);
    load();
  };

  const handleKirim = async (id) => {
    await api.update("LaporanHarian", id, { status: "Dikirim" });
    toast.success("Laporan dikirim untuk validasi");
    load();
  };

  const filtered = filterJenis === "Semua" ? list : list.filter((l) => l.jenis === filterJenis);

  const fotoFields = [
    { key: "distribusi", label: "Foto Distribusi", field: "foto_distribusi_url" },
    { key: "makanan", label: "Foto Makanan", field: "foto_makanan_url" },
  ];

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex flex-wrap gap-2">
          {["Semua", "Harian", "Mingguan", "Bulanan"].map((j) => (
            <button
              key={j}
              onClick={() => setFilterJenis(j)}
              className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterJenis === j ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
            >{j}</button>
          ))}
        </div>
        <Button size="sm" onClick={() => setShowForm(true)}>
          <Plus className="w-3.5 h-3.5 mr-1" />Buat Laporan
        </Button>
      </div>

      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-5">
          <h4 className="font-bold">Buat Laporan Baru</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">Jenis Laporan</label>
              <Select value={form.jenis} onValueChange={(v) => setForm({ ...form, jenis: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="Harian">Harian</SelectItem>
                  <SelectItem value="Mingguan">Mingguan</SelectItem>
                  <SelectItem value="Bulanan">Bulanan</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="Draft">Draft</SelectItem>
                  <SelectItem value="Dikirim">Dikirim</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Menu Pagi</label>
              <Input value={form.menu_pagi} onChange={(e) => setForm({ ...form, menu_pagi: e.target.value })} placeholder="Nasi, ayam, sayur..." />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Menu Siang</label>
              <Input value={form.menu_siang} onChange={(e) => setForm({ ...form, menu_siang: e.target.value })} placeholder="Nasi, ikan, buah..." />
            </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">Jumlah Terdistribusi</label>
              <Input type="number" value={form.jumlah_terdistribusi} onChange={(e) => setForm({ ...form, jumlah_terdistribusi: e.target.value })} placeholder="0" />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Biaya Operasional (Rp)</label>
              <Input type="number" value={form.biaya_operasional} onChange={(e) => setForm({ ...form, biaya_operasional: e.target.value })} placeholder="0" />
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-medium mb-1 block">Keterangan Operasional Dapur</label>
              <Textarea rows={3} value={form.operasional_dapur} onChange={(e) => setForm({ ...form, operasional_dapur: e.target.value })} placeholder="Kondisi dapur, peralatan, dll..." />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Kendala dan Catatan</label>
              <Textarea rows={3} value={form.kendala} onChange={(e) => setForm({ ...form, kendala: e.target.value })} placeholder="Kendala yang dihadapi..." />
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {fotoFields.map((f) => (
              <div key={f.key}>
                <label className="text-xs font-medium mb-1 block">{f.label}</label>
                <label className={`flex items-center gap-3 border-2 border-dashed rounded-xl p-3 cursor-pointer ${form[f.field] ? "border-emerald-400 bg-emerald-50" : "border-border hover:border-primary/50"}`}>
                  {form[f.field] ? (
                    <img src={form[f.field]} 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[f.key] ? "Mengupload..." : `Upload ${f.label.toLowerCase()}`}</span>
                    </>
                  )}
                  <input type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && handleUpload(f.key, e.target.files[0])} />
                </label>
              </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)}><X className="w-3.5 h-3.5 mr-1" />Batal</Button>
          </div>
        </div>
      )}

      <div className="space-y-3">
        {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>
        ) : filtered.length === 0 ? (
          <div className="text-center py-12 text-sm text-muted-foreground">Belum ada laporan.</div>
        ) : filtered.map((l) => (
          <div key={l.id} className="bg-card rounded-xl border border-border p-4">
            <div className="flex items-start justify-between gap-3 flex-wrap">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center flex-shrink-0">
                  <FileText className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <div className="flex items-center gap-2 flex-wrap">
                    <p className="font-bold text-foreground">{l.jenis} — {l.tanggal}</p>
                    <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${STATUS_COLORS[l.status]}`}>{l.status}</span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {l.jumlah_omprengan} omprengan · {l.jumlah_terdistribusi} terdistribusi
                    {l.menu_pagi && ` · Pagi: ${l.menu_pagi}`}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2 flex-shrink-0">
                {l.foto_distribusi_url && <a href={l.foto_distribusi_url} target="_blank" rel="noreferrer" className="text-xs text-primary hover:underline">Foto Distribusi</a>}
                {l.foto_makanan_url && <a href={l.foto_makanan_url} target="_blank" rel="noreferrer" className="text-xs text-primary hover:underline">Foto Makanan</a>}
                {l.status === "Draft" && (
                  <Button size="sm" variant="outline" onClick={() => handleKirim(l.id)}>
                    <CheckCircle className="w-3.5 h-3.5 mr-1" />Kirim
                  </Button>
                )}
              </div>
            </div>
            {(l.operasional_dapur || l.kendala) && (
              <div className="mt-3 pt-3 border-t border-border grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-muted-foreground">
                {l.operasional_dapur && <p><span className="font-semibold">Operasional:</span> {l.operasional_dapur}</p>}
                {l.kendala && <p><span className="font-semibold">Kendala:</span> {l.kendala}</p>}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}