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, User, ArrowLeft, Upload, Camera } from "lucide-react";
import { toast } from "sonner";

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

const JABATAN = ["Supir", "Kepala Koki", "Anggota Koki", "Tukang Packing", "Ahli Gizi", "Cuci Ompreng"];
const JABATAN_COLORS = {
  "Supir": "bg-blue-100 text-blue-700",
  "Kepala Koki": "bg-amber-100 text-amber-700",
  "Anggota Koki": "bg-orange-100 text-orange-700",
  "Tukang Packing": "bg-purple-100 text-purple-700",
  "Ahli Gizi": "bg-green-100 text-green-700",
  "Cuci Ompreng": "bg-teal-100 text-teal-700",
};

const emptyForm = { nama: "", jabatan: "", no_hp: "", no_ktp: "", alamat: "", gaji: "", no_sim: "", jenis_kendaraan: "", status: "Aktif", foto_url: "" };

export default function TabKaryawan({ 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 [filterJabatan, setFilterJabatan] = useState("Semua");
  const [selected, setSelected] = useState(null); // detail view
  const [uploading, setUploading] = useState(false);

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

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

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

  const handleSubmit = async () => {
    if (!form.nama || !form.jabatan) return toast.error("Nama dan jabatan wajib diisi");
    const payload = { ...form, sppg_id: sppgId, gaji: Number(form.gaji) };
    if (editId) {
      await api.update("Karyawan", editId, payload);
      toast.success("Data karyawan diperbarui");
    } else {
      await api.create("Karyawan", payload);
      toast.success("Karyawan berhasil ditambahkan");
    }
    setShowForm(false); setEditId(null); setForm(emptyForm); load();
  };

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

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

  const filtered = filterJabatan === "Semua" ? list : list.filter((k) => k.jabatan === filterJabatan);
  const totalGaji = list.reduce((acc, k) => acc + (k.gaji || 0), 0);
  const groupByJabatan = JABATAN.map((j) => ({ jabatan: j, count: list.filter((k) => k.jabatan === j).length, gaji: list.filter((k) => k.jabatan === j).reduce((a, k) => a + (k.gaji || 0), 0) }));

  // === DETAIL VIEW ===
  if (selected) {
    const k = selected;
    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
        </button>
        <div className="bg-card rounded-xl border border-border p-6">
          <div className="flex flex-col sm:flex-row items-start gap-6">
            <div className="flex flex-col items-center gap-3">
              {k.foto_url ? (
                <img src={k.foto_url} alt={k.nama} className="w-28 h-28 rounded-2xl object-cover border-2 border-border shadow" />
              ) : (
                <div className="w-28 h-28 bg-primary/10 rounded-2xl flex items-center justify-center">
                  <User className="w-12 h-12 text-primary/40" />
                </div>
              )}
              <span className={`px-3 py-1 rounded-full text-xs font-bold ${JABATAN_COLORS[k.jabatan] || "bg-muted text-muted-foreground"}`}>{k.jabatan}</span>
            </div>
            <div className="flex-1 space-y-4">
              <div>
                <h2 className="text-2xl font-black text-foreground">{k.nama}</h2>
                <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${k.status === "Aktif" ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-600"}`}>{k.status}</span>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {[
                  { label: "No. HP", value: k.no_hp },
                  { label: "No. KTP", value: k.no_ktp },
                  { label: "Alamat", value: k.alamat },
                  { label: "Gaji", value: formatRp(k.gaji) },
                  ...(k.jabatan === "Supir" ? [
                    { label: "No. SIM", value: k.no_sim },
                    { label: "Jenis Kendaraan", value: k.jenis_kendaraan },
                  ] : []),
                ].map((f) => (
                  <div key={f.label}>
                    <p className="text-xs text-muted-foreground">{f.label}</p>
                    <p className="text-sm font-semibold text-foreground">{f.value || "-"}</p>
                  </div>
                ))}
              </div>
              <div className="flex gap-2 pt-2">
                <Button size="sm" variant="outline" onClick={() => handleEdit(k)}><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(k.id)}><Trash2 className="w-3.5 h-3.5 mr-1" />Hapus</Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Summary */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        {groupByJabatan.map((g) => (
          <div key={g.jabatan} className="bg-card rounded-xl border border-border p-3">
            <p className="text-xs text-muted-foreground">{g.jabatan}</p>
            <p className="text-xl font-black text-foreground">{g.count} <span className="text-sm font-normal">org</span></p>
            <p className="text-xs text-primary font-medium">{formatRp(g.gaji)}</p>
          </div>
        ))}
      </div>

      <div className="bg-card rounded-xl border border-border p-4 flex items-center justify-between gap-3 flex-wrap">
        <p className="text-sm font-semibold text-foreground">Total Gaji: <span className="text-primary text-lg font-black">{formatRp(totalGaji)}</span></p>
        <Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm(emptyForm); }}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Karyawan
        </Button>
      </div>

      {/* Filter */}
      <div className="flex flex-wrap gap-2">
        {["Semua", ...JABATAN].map((j) => (
          <button key={j} onClick={() => setFilterJabatan(j)} className={`px-3 py-1.5 rounded-full text-xs font-semibold transition-colors ${filterJabatan === j ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/80"}`}>{j}</button>
        ))}
      </div>

      {/* Form */}
      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold text-foreground">{editId ? "Edit Karyawan" : "Tambah Karyawan Baru"}</h4>
          {/* Foto Upload */}
          <div>
            <label className="text-xs font-medium mb-2 block">Foto Profil</label>
            <label className={`flex items-center gap-3 border-2 border-dashed rounded-xl p-3 cursor-pointer w-fit ${form.foto_url ? "border-emerald-400 bg-emerald-50" : "border-border hover:border-primary/50"}`}>
              {form.foto_url ? (
                <img src={form.foto_url} alt="profil" className="w-20 h-20 rounded-xl object-cover" />
              ) : (
                <div className="w-20 h-20 bg-muted rounded-xl flex flex-col items-center justify-center gap-1">
                  <Camera className="w-6 h-6 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 Lengkap *</label><Input value={form.nama} onChange={(e) => setForm({ ...form, nama: e.target.value })} placeholder="Nama lengkap" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jabatan *</label>
              <Select value={form.jabatan} onValueChange={(v) => setForm({ ...form, jabatan: v })}>
                <SelectTrigger><SelectValue placeholder="Pilih jabatan" /></SelectTrigger>
                <SelectContent>{JABATAN.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">Gaji (Rp)</label><Input type="number" value={form.gaji} onChange={(e) => setForm({ ...form, gaji: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">No. HP</label><Input value={form.no_hp} onChange={(e) => setForm({ ...form, no_hp: e.target.value })} placeholder="08xx" /></div>
            <div><label className="text-xs font-medium mb-1 block">No. KTP</label><Input value={form.no_ktp} onChange={(e) => setForm({ ...form, no_ktp: e.target.value })} placeholder="NIK" /></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="Alamat" /></div>
            {form.jabatan === "Supir" && <>
              <div><label className="text-xs font-medium mb-1 block">No. SIM</label><Input value={form.no_sim} onChange={(e) => setForm({ ...form, no_sim: e.target.value })} placeholder="Nomor SIM" /></div>
              <div><label className="text-xs font-medium mb-1 block">Jenis Kendaraan</label><Input value={form.jenis_kendaraan} onChange={(e) => setForm({ ...form, jenis_kendaraan: e.target.value })} placeholder="Motor/Mobil" /></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 Karyawan — klik untuk detail */}
      {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-muted-foreground text-sm">Belum ada karyawan. Tambahkan karyawan baru.</div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
          {filtered.map((k) => (
            <button
              key={k.id}
              onClick={() => setSelected(k)}
              className="bg-card rounded-xl border border-border p-4 hover:shadow-md hover:-translate-y-0.5 transition-all text-left group"
            >
              <div className="flex flex-col items-center gap-3">
                {k.foto_url ? (
                  <img src={k.foto_url} alt={k.nama} className="w-20 h-20 rounded-xl object-cover border border-border" />
                ) : (
                  <div className="w-20 h-20 bg-primary/10 rounded-xl flex items-center justify-center group-hover:bg-primary/15 transition-colors">
                    <User className="w-9 h-9 text-primary/40" />
                  </div>
                )}
                <div className="text-center">
                  <p className="text-sm font-bold text-foreground group-hover:text-primary transition-colors leading-tight">{k.nama}</p>
                  <span className={`mt-1 inline-block px-2 py-0.5 rounded-full text-xs font-semibold ${JABATAN_COLORS[k.jabatan] || "bg-muted text-muted-foreground"}`}>{k.jabatan}</span>
                </div>
                <p className="text-xs font-semibold text-primary">{formatRp(k.gaji)}</p>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}