import { useState, useEffect } from "react";
import {
  Send,
  Hash,
  Search,
  Trash2,
  RefreshCw,
  Upload,
  Image as ImageIcon,
  Building2,
  History,
  ShieldCheck,
} from "lucide-react";

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 { Badge } from "@/components/ui/badge";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import DetailRiwayatPengaduan from "../components/DetailRiwayatPengaduan";
import { createAuditLog } from "../utils/auditLogger";

const LIST_API = "http://localhost/backend/api/pengaduan/list.php";
const CREATE_API = "http://localhost/backend/api/pengaduan/create.php";
const UPDATE_STATUS_API = "http://localhost/backend/api/pengaduan/update_status.php";
const DELETE_API = "http://localhost/backend/api/pengaduan/delete.php";
const SPPG_API = "http://localhost/backend/api/sppg/list.php";

const statusColors = {
  Baru: "bg-blue-100 text-blue-700",
  Diproses: "bg-amber-100 text-amber-700",
  Selesai: "bg-emerald-100 text-emerald-700",
};

const statusAlurColors = {
  "Menunggu Validasi": "bg-blue-100 text-blue-700",
  "Tidak Valid": "bg-red-100 text-red-700",
  Valid: "bg-emerald-100 text-emerald-700",
  "Diproses Pemerintah": "bg-amber-100 text-amber-700",
  "Menunggu Validasi Perbaikan": "bg-purple-100 text-purple-700",
  "Masih Bermasalah": "bg-red-100 text-red-700",
  Selesai: "bg-emerald-100 text-emerald-700",
};

export default function Pengaduan() {
  const role = localStorage.getItem("role");

  const isAdmin = role === "admin";
  const isPemerintah = role === "pemerintah";
  const isValidator = role === "validator";

  // Semua role, termasuk masyarakat/publik, boleh melihat daftar pengaduan
  // untuk transparansi. Tapi data pribadi tetap disamarkan.
  const canSeePengaduanList = true;
  const canSeeDataPribadi = isAdmin || isPemerintah || isValidator;

  const [list, setList] = useState([]);
  const [sppgList, setSppgList] = useState([]);
  const [loading, setLoading] = useState(true);

  const [filterStatus, setFilterStatus] = useState("Semua");
  const [searchTerm, setSearchTerm] = useState("");

  const [submitting, setSubmitting] = useState(false);
  const [ticketId, setTicketId] = useState(null);
  const [error, setError] = useState("");

  const [selectedRiwayatId, setSelectedRiwayatId] = useState(null);

  const [form, setForm] = useState({
    sppg_id: "",
    nama: "",
    kontak: "",
    kategori: "",
    isi: "",
  });

  const [foto, setFoto] = useState(null);
  const [fotoPreview, setFotoPreview] = useState("");

  useEffect(() => {
    loadData();
    loadSPPG();
  }, []);

  const maskNama = (nama, id) => {
    if (canSeeDataPribadi) {
      return nama || "-";
    }

    return `Pelapor #${id || "-"}`;
  };

  const maskKontak = (kontak) => {
    if (!kontak) return "-";

    if (canSeeDataPribadi) {
      return kontak;
    }

    const text = String(kontak).trim();

    if (text.includes("@")) {
      const [name, domain] = text.split("@");
      const safeName =
        name.length <= 2 ? `${name[0] || "*"}***` : `${name.slice(0, 2)}***`;

      return `${safeName}@${domain || "***"}`;
    }

    if (text.length <= 4) {
      return "****";
    }

    return `${text.slice(0, 3)}****${text.slice(-2)}`;
  };

  const loadSPPG = async () => {
    try {
      const res = await fetch(SPPG_API);
      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setSppgList(result.data);
      } else {
        setSppgList([]);
      }
    } catch (err) {
      console.error("Gagal mengambil data SPPG:", err);
      setSppgList([]);
    }
  };

  const loadData = async () => {
    try {
      setLoading(true);
      setError("");

      const res = await fetch(LIST_API);

      if (!res.ok) {
        throw new Error(`HTTP Error ${res.status}`);
      }

      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setList(result.data);
      } else {
        setList([]);
        setError(result.message || "Format data pengaduan tidak sesuai");
      }
    } catch (err) {
      console.error("Gagal mengambil pengaduan:", err);
      setList([]);
      setError("Gagal mengambil data pengaduan dari server");
    } finally {
      setLoading(false);
    }
  };

  const handleFotoChange = (e) => {
    const file = e.target.files?.[0];

    if (!file) return;

    const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/webp"];

    if (!allowedTypes.includes(file.type)) {
      alert("Format foto harus JPG, JPEG, PNG, atau WEBP");
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      alert("Ukuran foto maksimal 5MB");
      return;
    }

    setFoto(file);
    setFotoPreview(URL.createObjectURL(file));
  };

  const clearFoto = () => {
    setFoto(null);
    setFotoPreview("");
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!form.sppg_id || !form.nama || !form.kategori || !form.isi) {
      alert("Mohon pilih SPPG, isi nama, kategori, dan isi pengaduan.");
      return;
    }

    if (!foto) {
      alert("Mohon upload foto bukti pengaduan.");
      return;
    }

    try {
      setSubmitting(true);

      const formData = new FormData();
      formData.append("sppg_id", form.sppg_id);
      formData.append("nama", form.nama);
      formData.append("kontak", form.kontak);
      formData.append("kategori", form.kategori);
      formData.append("isi", form.isi);
      formData.append("foto", foto);

      const res = await fetch(CREATE_API, {
        method: "POST",
        body: formData,
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal mengirim pengaduan");
        return;
      }

      const newId = result.data?.id || "-";
      setTicketId(newId);

      createAuditLog({
        aksi: "Membuat Pengaduan",
        target: "Pengaduan",
        keterangan: `Pengaduan baru dikirim oleh ${form.nama} dengan kategori ${form.kategori}.`,
      });

      setForm({
        sppg_id: "",
        nama: "",
        kontak: "",
        kategori: "",
        isi: "",
      });

      clearFoto();

      await loadData();
    } catch (err) {
      console.error("Gagal mengirim pengaduan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdateStatus = async (item, status) => {
    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat mengubah status pengaduan.");
      return;
    }

    const statusLama = item.status || "-";

    try {
      const res = await fetch(`${UPDATE_STATUS_API}?id=${item.id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ status }),
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal memperbarui status");
        return;
      }

      createAuditLog({
        aksi: "Mengubah Status Pengaduan",
        target: "Pengaduan",
        keterangan: `Admin mengubah status pengaduan ID ${item.id} dari ${statusLama} menjadi ${status}.`,
      });

      await loadData();
    } catch (err) {
      console.error("Gagal update status:", err);
      alert("Tidak bisa terhubung ke server");
    }
  };

  const handleDelete = async (item) => {
    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat menghapus pengaduan.");
      return;
    }

    const yakin = window.confirm("Yakin ingin menghapus pengaduan ini?");

    if (!yakin) return;

    try {
      const res = await fetch(`${DELETE_API}?id=${item.id}`, {
        method: "DELETE",
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal menghapus pengaduan");
        return;
      }

      createAuditLog({
        aksi: "Menghapus Pengaduan",
        target: "Pengaduan",
        keterangan: `Admin menghapus pengaduan ID ${item.id} dari ${item.nama || "-"}.`,
      });

      await loadData();
    } catch (err) {
      console.error("Gagal hapus pengaduan:", err);
      alert("Tidak bisa terhubung ke server");
    }
  };

  const filteredList = list
    .filter((p) => filterStatus === "Semua" || p.status === filterStatus)
    .filter((p) => {
      const keyword = searchTerm.toLowerCase();

      return (
        !keyword ||
        (p.nama || "").toLowerCase().includes(keyword) ||
        (p.kontak || "").toLowerCase().includes(keyword) ||
        (p.kategori || "").toLowerCase().includes(keyword) ||
        (p.isi || "").toLowerCase().includes(keyword) ||
        (p.status || "").toLowerCase().includes(keyword) ||
        (p.status_alur || "").toLowerCase().includes(keyword) ||
        (p.sppg_nama || "").toLowerCase().includes(keyword) ||
        (p.sppg_kabupaten || "").toLowerCase().includes(keyword) ||
        (p.sppg_provinsi || "").toLowerCase().includes(keyword)
      );
    });

  const exportCSV = () => {
    if (filteredList.length === 0) {
      alert("Tidak ada data pengaduan untuk diunduh.");
      return;
    }

    const headers = [
      "ID",
      "Tanggal",
      "SPPG Diadukan",
      "Kabupaten",
      "Provinsi",
      "Nama",
      "Kontak",
      "Kategori",
      "Isi",
      "Status",
      "Status Alur",
      "Foto",
    ];

    const rows = filteredList.map((p) => [
      p.id || "",
      p.created_at || "",
      p.sppg_nama || "",
      p.sppg_kabupaten || "",
      p.sppg_provinsi || "",
      p.nama || "",
      p.kontak || "",
      p.kategori || "",
      p.isi || "",
      p.status || "",
      p.status_alur || "",
      p.bukti_url || "",
    ]);

    const csvContent = [headers, ...rows]
      .map((row) =>
        row
          .map((cell) => {
            const value = String(cell).replace(/"/g, '""');
            return `"${value}"`;
          })
          .join(",")
      )
      .join("\n");

    const blob = new Blob([`\uFEFF${csvContent}`], {
      type: "text/csv;charset=utf-8;",
    });

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");

    link.href = url;
    link.download = "laporan-pengaduan.csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    createAuditLog({
      aksi: "Export Pengaduan",
      target: "Pengaduan",
      keterangan: "Admin mengunduh data pengaduan dalam format CSV.",
    });
  };

  const totalBaru = list.filter((p) => p.status === "Baru").length;
  const totalDiproses = list.filter((p) => p.status === "Diproses").length;
  const totalSelesai = list.filter((p) => p.status === "Selesai").length;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
      <div className="mb-10">
        <div className="relative overflow-hidden rounded-[2.25rem] border border-white/10 bg-gradient-to-br from-[#23486b] via-[#2450d3] to-[#1b8d93] text-white shadow-[0_20px_70px_rgba(2,8,23,0.22)]">
          <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.06)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[size:70px_70px] opacity-45" />
          <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(255,255,255,0.16),transparent_28%),radial-gradient(circle_at_top_right,rgba(96,165,250,0.18),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(45,212,191,0.16),transparent_28%)]" />

          <div className="relative z-10 px-5 py-10 text-center sm:px-8 sm:py-12 lg:px-12 lg:py-16">
            <div className="inline-flex items-center rounded-full border border-white/15 bg-white/10 px-5 py-2 text-sm font-bold uppercase tracking-[0.18em] text-blue-50 shadow-lg backdrop-blur-md">
              Kanal Aspirasi Publik
            </div>

            <h1 className="mx-auto mt-6 max-w-full whitespace-nowrap text-3xl font-black leading-[1.05] tracking-tight text-white drop-shadow-[0_4px_16px_rgba(0,0,0,0.25)] sm:text-4xl lg:text-5xl xl:text-6xl">
              <span className="text-white">Pengaduan </span>
              <span className="bg-gradient-to-r from-cyan-200 via-sky-100 to-teal-200 bg-clip-text text-transparent">
                Masyarakat
              </span>
            </h1>

            <p className="mx-auto mt-5 max-w-4xl text-base leading-relaxed text-blue-50/90 sm:text-lg lg:text-xl">
              Laporkan kendala atau dugaan penyimpangan terkait SPPG tertentu dengan bukti foto agar proses verifikasi dan tindak lanjut lebih cepat, jelas, dan transparan.
            </p>

            <div className="mt-8 flex flex-wrap justify-center gap-3">
              {isAdmin && (
                <Button
                  variant="outline"
                  onClick={exportCSV}
                  className="rounded-full bg-white px-6 py-3 font-bold text-[#1f4ecb] shadow-lg hover:bg-blue-50"
                >
                  Export CSV
                </Button>
              )}

              <Button
                variant="outline"
                onClick={loadData}
                className="rounded-full border-white/25 bg-white/10 px-6 py-3 font-bold text-white shadow-lg backdrop-blur-md hover:bg-white/20 hover:text-white"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                Refresh Data
              </Button>
            </div>
          </div>
        </div>
      </div>

      {error && (
        <div className="mb-5 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-10">
        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 sm:p-6">
          {ticketId && (
            <div className="mb-4 bg-emerald-50 border border-emerald-200 rounded-xl p-4">
              <p className="text-sm font-semibold text-emerald-700">
                Pengaduan berhasil dikirim!
              </p>

              <div className="flex items-center gap-2 mt-1">
                <Hash className="w-4 h-4 text-emerald-600" />
                <p className="text-sm font-mono font-bold text-emerald-700">
                  ID Pengaduan: {ticketId}
                </p>
              </div>

              <p className="text-xs text-emerald-600 mt-1">
                Simpan ID ini sebagai bukti pengaduan.
              </p>
            </div>
          )}

          <h3 className="font-bold text-foreground mb-4">Tulis Pengaduan</h3>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                SPPG yang Diadukan *
              </label>

              <Select
                value={form.sppg_id}
                onValueChange={(v) => setForm({ ...form, sppg_id: v })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Pilih SPPG yang diadukan" />
                </SelectTrigger>

                <SelectContent>
                  {sppgList.map((s) => (
                    <SelectItem key={s.id} value={String(s.id)}>
                      {s.nama} - {s.kabupaten}, {s.provinsi}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <p className="mt-1 text-xs text-muted-foreground">
                Pilih SPPG agar pengaduan jelas ditujukan ke dapur/wilayah yang benar.
              </p>
            </div>

            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                Nama Pelapor *
              </label>

              <Input
                placeholder="Nama Anda"
                value={form.nama}
                onChange={(e) => setForm({ ...form, nama: e.target.value })}
              />
            </div>

            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                Kontak
              </label>

              <Input
                placeholder="Nomor HP atau email"
                value={form.kontak}
                onChange={(e) => setForm({ ...form, kontak: e.target.value })}
              />
            </div>

            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                Kategori Pengaduan *
              </label>

              <Select
                value={form.kategori}
                onValueChange={(v) => setForm({ ...form, kategori: v })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Pilih kategori" />
                </SelectTrigger>

                <SelectContent>
                  {[
                    "Distribusi",
                    "Kualitas Makanan",
                    "Dana",
                    "Data Siswa",
                    "Kebersihan",
                    "Lainnya",
                  ].map((k) => (
                    <SelectItem key={k} value={k}>
                      {k}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                Isi Pengaduan *
              </label>

              <Textarea
                rows={5}
                placeholder="Jelaskan pengaduan Anda secara detail..."
                value={form.isi}
                onChange={(e) => setForm({ ...form, isi: e.target.value })}
              />
            </div>

            <div>
              <label className="text-sm font-medium text-foreground mb-1.5 block">
                Foto Bukti *
              </label>

              <label className="flex flex-col items-center justify-center gap-3 border-2 border-dashed rounded-xl p-5 cursor-pointer hover:border-primary/50 transition-colors">
                {fotoPreview ? (
                  <div className="w-full">
                    <img
                      src={fotoPreview}
                      alt="Preview bukti"
                      className="w-full max-h-64 object-cover rounded-lg border"
                    />

                    <button
                      type="button"
                      onClick={(e) => {
                        e.preventDefault();
                        clearFoto();
                      }}
                      className="mt-3 text-sm text-red-600 hover:underline"
                    >
                      Hapus foto
                    </button>
                  </div>
                ) : (
                  <>
                    <Upload className="w-8 h-8 text-muted-foreground" />
                    <div className="text-center">
                      <p className="text-sm font-medium">
                        Klik untuk upload foto bukti
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        JPG, JPEG, PNG, atau WEBP. Maksimal 5MB.
                      </p>
                    </div>
                  </>
                )}

                <input
                  type="file"
                  accept="image/jpeg,image/jpg,image/png,image/webp"
                  className="hidden"
                  onChange={handleFotoChange}
                />
              </label>
            </div>

            <Button type="submit" className="w-full rounded-full" disabled={submitting}>
              {submitting ? (
                <span className="flex items-center gap-2">
                  <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Mengirim...
                </span>
              ) : (
                <span className="flex items-center gap-2">
                  <Send className="w-4 h-4" />
                  Kirim Pengaduan
                </span>
              )}
            </Button>
          </form>
        </div>

        <div className="bg-card rounded-2xl border border-border/80 p-5 shadow-sm shadow-slate-200/60 sm:p-6">
          <h3 className="font-bold text-foreground mb-4">Statistik Pengaduan</h3>

          <div className="grid grid-cols-2 gap-3">
            <div className="rounded-xl border border-border p-4">
              <p className="text-sm text-muted-foreground">Total Pengaduan</p>
              <p className="text-2xl font-bold">{list.length}</p>
            </div>

            <div className="rounded-xl border border-border p-4">
              <p className="text-sm text-muted-foreground">Baru</p>
              <p className="text-2xl font-bold text-blue-600">{totalBaru}</p>
            </div>

            <div className="rounded-xl border border-border p-4">
              <p className="text-sm text-muted-foreground">Diproses</p>
              <p className="text-2xl font-bold text-amber-600">{totalDiproses}</p>
            </div>

            <div className="rounded-xl border border-border p-4">
              <p className="text-sm text-muted-foreground">Selesai</p>
              <p className="text-2xl font-bold text-emerald-600">{totalSelesai}</p>
            </div>
          </div>

          <p className="text-sm text-muted-foreground mt-4">
            Setiap pengaduan wajib memilih SPPG tujuan dan menyertakan foto bukti agar laporan mudah diverifikasi.
          </p>
        </div>
      </div>

      <div className="mb-6 rounded-xl border border-blue-100 bg-blue-50 p-5 text-sm text-blue-800">
        <div className="flex items-start gap-3">
          <ShieldCheck className="mt-0.5 h-5 w-5 flex-shrink-0" />

          <div>
            <p className="font-bold">Transparansi Pengaduan Publik</p>
            <p className="mt-1 leading-relaxed">
              Masyarakat dapat melihat kategori pengaduan, SPPG terkait,
              provinsi/kabupaten, isi pengaduan, status, tanggal masuk, dan
              riwayat tindak lanjut. Kontak pelapor, nomor HP, email, dan data
              pribadi sensitif disamarkan untuk menjaga privasi.
            </p>
          </div>
        </div>
      </div>

      {canSeePengaduanList && (
        <div className="bg-card rounded-2xl border border-border/80 overflow-hidden shadow-sm shadow-slate-200/60">
          <div className="p-5 sm:p-6 border-b border-border space-y-3">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />

              <input
                placeholder="Cari pengaduan, SPPG, wilayah, kategori, status..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-9 pr-4 h-9 rounded-lg border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div className="flex flex-wrap gap-2">
              {["Semua", "Baru", "Diproses", "Selesai"].map((s) => (
                <button
                  key={s}
                  onClick={() => setFilterStatus(s)}
                  className={`px-3.5 py-1.5 rounded-full text-xs font-semibold transition-colors ${
                    filterStatus === s
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted text-muted-foreground hover:bg-muted/80"
                  }`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="w-7 h-7 border-2 border-primary/20 border-t-primary rounded-full animate-spin" />
            </div>
          ) : filteredList.length === 0 ? (
            <div className="text-center py-16 text-muted-foreground text-sm">
              Belum ada pengaduan.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-primary/5">
                    <TableHead className="text-primary font-semibold">ID</TableHead>
                    <TableHead className="text-primary font-semibold">Tanggal</TableHead>
                    <TableHead className="text-primary font-semibold">SPPG Terkait</TableHead>
                    <TableHead className="text-primary font-semibold">Pelapor</TableHead>
                    <TableHead className="text-primary font-semibold">Kontak</TableHead>
                    <TableHead className="text-primary font-semibold">Kategori</TableHead>
                    <TableHead className="text-primary font-semibold">Isi Pengaduan</TableHead>
                    <TableHead className="text-primary font-semibold">Bukti</TableHead>
                    <TableHead className="text-primary font-semibold">Status</TableHead>
                    <TableHead className="text-primary font-semibold">Alur</TableHead>
                    <TableHead className="text-primary font-semibold text-center">
                      Tindak Lanjut
                    </TableHead>
                    {isAdmin && (
                      <TableHead className="text-primary font-semibold text-center">
                        Aksi
                      </TableHead>
                    )}
                  </TableRow>
                </TableHeader>

                <TableBody>
                  {filteredList.map((p) => (
                    <TableRow key={p.id} className="hover:bg-muted/30">
                      <TableCell className="font-mono text-xs text-muted-foreground">
                        #{p.id}
                      </TableCell>

                      <TableCell className="text-sm whitespace-nowrap">
                        {p.created_at
                          ? new Date(p.created_at).toLocaleDateString("id-ID", {
                              day: "numeric",
                              month: "short",
                              year: "numeric",
                            })
                          : "-"}
                      </TableCell>

                      <TableCell className="text-sm min-w-52">
                        <div className="flex items-start gap-2">
                          <Building2 className="w-4 h-4 text-primary mt-0.5 flex-shrink-0" />
                          <div>
                            <p className="font-semibold text-foreground">
                              {p.sppg_nama || "SPPG belum dipilih"}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {p.sppg_kabupaten || "-"}, {p.sppg_provinsi || "-"}
                            </p>
                          </div>
                        </div>
                      </TableCell>

                      <TableCell className="text-sm font-medium">
                        {maskNama(p.nama, p.id)}
                      </TableCell>

                      <TableCell className="text-sm text-muted-foreground">
                        {maskKontak(p.kontak)}
                      </TableCell>

                      <TableCell className="text-sm">{p.kategori || "-"}</TableCell>

                      <TableCell className="text-sm max-w-xs">
                        <p className="line-clamp-2">{p.isi || "-"}</p>
                      </TableCell>

                      <TableCell>
                        {p.bukti_url ? (
                          <a
                            href={p.bukti_url}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
                          >
                            <ImageIcon className="w-4 h-4" />
                            Lihat
                          </a>
                        ) : (
                          <span className="text-xs text-muted-foreground">-</span>
                        )}
                      </TableCell>

                      <TableCell>
                        {isAdmin ? (
                          <select
                            value={p.status}
                            onChange={(e) => handleUpdateStatus(p, e.target.value)}
                            className="rounded-md border border-input bg-background px-2 py-1 text-xs"
                          >
                            <option value="Baru">Baru</option>
                            <option value="Diproses">Diproses</option>
                            <option value="Selesai">Selesai</option>
                          </select>
                        ) : (
                          <Badge
                            className={`${
                              statusColors[p.status] || "bg-muted"
                            } border-0 font-medium`}
                          >
                            {p.status}
                          </Badge>
                        )}
                      </TableCell>

                      <TableCell>
                        <Badge
                          className={`${
                            statusAlurColors[p.status_alur] || "bg-muted"
                          } border-0 font-medium`}
                        >
                          {p.status_alur || "-"}
                        </Badge>
                      </TableCell>

                      <TableCell className="text-center">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => setSelectedRiwayatId(p.id)}
                        >
                          <History className="w-4 h-4 mr-1" />
                          Detail
                        </Button>
                      </TableCell>

                      {isAdmin && (
                        <TableCell className="text-center">
                          <Button
                            size="sm"
                            variant="destructive"
                            onClick={() => handleDelete(p)}
                          >
                            <Trash2 className="w-4 h-4 mr-1" />
                            Hapus
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </div>
      )}

      {selectedRiwayatId && (
        <DetailRiwayatPengaduan
          pengaduanId={selectedRiwayatId}
          onClose={() => setSelectedRiwayatId(null)}
        />
      )}
    </div>
  );
}