import { useEffect, useState } from "react";
import {
  Search,
  RefreshCw,
  ShieldCheck,
  Clock,
  CheckCircle2,
  AlertTriangle,
  History,
  Building2,
  Image as ImageIcon,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

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

import DetailRiwayatPengaduan from "../../components/DetailRiwayatPengaduan";

const LIST_API = "http://localhost/backend/api/pengaduan/list.php";

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 Perbaikan SPPG": "bg-orange-100 text-orange-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",
};

const normalize = (value) => String(value || "").trim();

const isPerluValidasi = (p) => {
  const alur = normalize(p.status_alur);
  const status = normalize(p.status);

  return (
    alur === "Menunggu Validasi" ||
    alur === "Menunggu Validasi Perbaikan" ||
    status === "Baru"
  );
};

const isValidasiAwal = (p) => {
  const alur = normalize(p.status_alur);
  const status = normalize(p.status);
  const validasiStatus = normalize(p.validasi_status);

  return (
    alur === "Menunggu Validasi" ||
    (status === "Baru" && validasiStatus === "")
  );
};

const isValidasiPerbaikan = (p) => {
  const alur = normalize(p.status_alur);

  return alur === "Menunggu Validasi Perbaikan";
};

const isSelesaiAtauDitolak = (p) => {
  const alur = normalize(p.status_alur);

  return alur === "Selesai" || alur === "Tidak Valid";
};

export default function ValidasiPengaduan() {
  const [list, setList] = useState([]);
  const [filtered, setFiltered] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterTahap, setFilterTahap] = useState("perlu_validasi");
  const [loading, setLoading] = useState(true);
  const [selectedRiwayatId, setSelectedRiwayatId] = useState(null);

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

      const res = await fetch(LIST_API);
      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setList(result.data);
      } else {
        setList([]);
      }
    } catch (err) {
      console.error("Gagal mengambil pengaduan:", err);
      setList([]);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    const keyword = searchTerm.toLowerCase();

    let data = [...list];

    if (filterTahap === "perlu_validasi") {
      data = data.filter(isPerluValidasi);
    }

    if (filterTahap === "validasi_awal") {
      data = data.filter(isValidasiAwal);
    }

    if (filterTahap === "validasi_perbaikan") {
      data = data.filter(isValidasiPerbaikan);
    }

    if (filterTahap === "selesai") {
      data = data.filter(isSelesaiAtauDitolak);
    }

    if (filterTahap === "semua") {
      data = [...list];
    }

    data = data.filter((p) => {
      return (
        !keyword ||
        (p.nama || "").toLowerCase().includes(keyword) ||
        (p.kategori || "").toLowerCase().includes(keyword) ||
        (p.isi || "").toLowerCase().includes(keyword) ||
        (p.sppg_nama || "").toLowerCase().includes(keyword) ||
        (p.sppg_kabupaten || "").toLowerCase().includes(keyword) ||
        (p.sppg_provinsi || "").toLowerCase().includes(keyword) ||
        (p.status || "").toLowerCase().includes(keyword) ||
        (p.status_alur || "").toLowerCase().includes(keyword)
      );
    });

    setFiltered(data);
  }, [list, searchTerm, filterTahap]);

  const totalPerluValidasi = list.filter(isPerluValidasi).length;
  const totalValidasiAwal = list.filter(isValidasiAwal).length;
  const totalValidasiPerbaikan = list.filter(isValidasiPerbaikan).length;
  const totalSelesai = list.filter(isSelesaiAtauDitolak).length;

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Validasi Pengaduan
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Validasi pengaduan awal dan validasi hasil perbaikan SPPG dengan bukti foto serta file.
          </p>
        </div>

        <Button variant="outline" onClick={loadData}>
          <RefreshCw className="w-4 h-4 mr-2" />
          Refresh
        </Button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
        <div className="rounded-xl border bg-card p-4">
          <div className="flex items-center gap-2 text-blue-700">
            <ShieldCheck className="w-5 h-5" />
            <p className="text-sm font-bold">Perlu Validasi</p>
          </div>
          <p className="text-2xl font-black mt-2">{totalPerluValidasi}</p>
        </div>

        <div className="rounded-xl border bg-card p-4">
          <div className="flex items-center gap-2 text-amber-700">
            <Clock className="w-5 h-5" />
            <p className="text-sm font-bold">Validasi Awal</p>
          </div>
          <p className="text-2xl font-black mt-2">{totalValidasiAwal}</p>
        </div>

        <div className="rounded-xl border bg-card p-4">
          <div className="flex items-center gap-2 text-purple-700">
            <AlertTriangle className="w-5 h-5" />
            <p className="text-sm font-bold">Validasi Perbaikan</p>
          </div>
          <p className="text-2xl font-black mt-2">{totalValidasiPerbaikan}</p>
        </div>

        <div className="rounded-xl border bg-card p-4">
          <div className="flex items-center gap-2 text-emerald-700">
            <CheckCircle2 className="w-5 h-5" />
            <p className="text-sm font-bold">Selesai/Ditolak</p>
          </div>
          <p className="text-2xl font-black mt-2">{totalSelesai}</p>
        </div>
      </div>

      <div className="rounded-xl border bg-card overflow-hidden">
        <div className="p-5 border-b 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, kategori, wilayah..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full h-10 rounded-lg border bg-background pl-9 pr-4 text-sm outline-none focus:ring-2 focus:ring-ring"
            />
          </div>

          <div className="flex flex-wrap gap-2">
            {[
              ["perlu_validasi", "Perlu Validasi"],
              ["validasi_awal", "Validasi Awal"],
              ["validasi_perbaikan", "Validasi Perbaikan"],
              ["selesai", "Selesai/Ditolak"],
              ["semua", "Semua"],
            ].map(([value, label]) => (
              <button
                key={value}
                onClick={() => setFilterTahap(value)}
                className={`px-3.5 py-1.5 rounded-full text-xs font-bold transition ${
                  filterTahap === value
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted text-muted-foreground hover:bg-muted/80"
                }`}
              >
                {label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-16">
            <div className="w-8 h-8 border-2 border-primary/20 border-t-primary rounded-full animate-spin" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="py-16 text-center text-sm text-muted-foreground">
            Tidak ada pengaduan pada filter ini.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-primary/5">
                  <TableHead>ID</TableHead>
                  <TableHead>Tanggal</TableHead>
                  <TableHead>SPPG</TableHead>
                  <TableHead>Kategori</TableHead>
                  <TableHead>Isi</TableHead>
                  <TableHead>Bukti Awal</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Status Alur</TableHead>
                  <TableHead className="text-center">Aksi</TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                {filtered.map((p) => (
                  <TableRow key={p.id}>
                    <TableCell className="font-mono text-xs">#{p.id}</TableCell>

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

                    <TableCell className="min-w-52">
                      <div className="flex items-start gap-2">
                        <Building2 className="w-4 h-4 text-primary mt-0.5" />
                        <div>
                          <p className="text-sm font-bold">
                            {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">{p.kategori || "-"}</TableCell>

                    <TableCell className="max-w-xs text-sm">
                      <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 font-bold text-primary hover:underline"
                        >
                          <ImageIcon className="w-4 h-4" />
                          Lihat
                        </a>
                      ) : (
                        <span className="text-xs text-muted-foreground">-</span>
                      )}
                    </TableCell>

                    <TableCell className="text-sm font-semibold">
                      {p.status || "-"}
                    </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"
                        onClick={() => setSelectedRiwayatId(p.id)}
                      >
                        <History className="w-4 h-4 mr-1" />
                        Detail & Validasi
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </div>

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