import { useState, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import {
  Search,
  Filter,
  Eye,
  RefreshCw,
  Plus,
  Pencil,
  Trash2,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

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

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

const LIST_API = "http://localhost/backend/api/sppg/list.php";
const DELETE_API = "http://localhost/backend/api/sppg/delete.php";

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

export default function DaftarSPPG() {
  const location = useLocation();

  const role = localStorage.getItem("role");
  const isAdminPage = location.pathname.startsWith("/admin/sppg");
  const isAdmin = role === "admin" && isAdminPage;

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

  const [searchTerm, setSearchTerm] = useState("");
  const [filterProvinsi, setFilterProvinsi] = useState("all");
  const [filterKabupaten, setFilterKabupaten] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");

  const [error, setError] = useState("");

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

  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)) {
        setSppgList(result.data);
      } else {
        setSppgList([]);
        setError(result.message || "Format data tidak sesuai");
      }
    } catch (err) {
      console.error("Gagal ambil data SPPG:", err);
      setSppgList([]);
      setError("Gagal mengambil data dari server");
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

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

    if (!yakin) return;

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

      const result = await res.json();

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

      alert("Data SPPG berhasil dihapus");
      loadData();
    } catch (err) {
      console.error("Gagal hapus data SPPG:", err);
      alert("Tidak bisa terhubung ke server");
    }
  };

  const provinsiList = [
    ...new Set(sppgList.map((s) => s.provinsi).filter(Boolean)),
  ];

  const kabupatenList = [
    ...new Set(
      sppgList
        .filter(
          (s) =>
            filterProvinsi === "all" ||
            s.provinsi === filterProvinsi
        )
        .map((s) => s.kabupaten)
        .filter(Boolean)
    ),
  ];

  const filtered = sppgList.filter((s) => {
    const keyword = searchTerm.toLowerCase();

    const matchSearch =
      (s.nama || "").toLowerCase().includes(keyword) ||
      (s.provinsi || "").toLowerCase().includes(keyword) ||
      (s.kabupaten || "").toLowerCase().includes(keyword) ||
      (s.alamat || "").toLowerCase().includes(keyword);

    const matchProv =
      filterProvinsi === "all" || s.provinsi === filterProvinsi;

    const matchKab =
      filterKabupaten === "all" || s.kabupaten === filterKabupaten;

    const matchStatus =
      filterStatus === "all" || s.status === filterStatus;

    return matchSearch && matchProv && matchKab && matchStatus;
  });

  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">
              {isAdmin ? "Dashboard Admin" : "Portal Masyarakat"}
            </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">{isAdmin ? "Manajemen Data " : "Daftar SPPG "}</span>
              <span className="bg-gradient-to-r from-cyan-200 via-sky-100 to-teal-200 bg-clip-text text-transparent">
                {isAdmin ? "Nasional" : "Publik"}
              </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">
              {isAdmin
                ? "Kelola data SPPG secara terpusat mulai dari penambahan, pembaruan, hingga penghapusan data dengan tampilan yang lebih rapi dan profesional."
                : "Pantau data SPPG, wilayah, dana, jumlah siswa, dan status operasional secara transparan melalui halaman publik yang lebih jelas."}
            </p>

            <div className="mt-8 flex flex-wrap justify-center gap-3">
              {isAdmin && (
                <Link to="/admin/sppg/tambah">
                  <Button className="rounded-full bg-white px-6 py-3 font-bold text-[#1f4ecb] shadow-lg hover:bg-blue-50">
                    <Plus className="w-4 h-4 mr-2" />
                    Tambah SPPG
                  </Button>
                </Link>
              )}

              <Button
                onClick={loadData}
                variant="outline"
                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>

      <div className="bg-card rounded-xl border border-border p-4 sm:p-5 mb-6">
        <div className="flex flex-col gap-3">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />

              <Input
                placeholder="Cari SPPG, provinsi, kabupaten, atau alamat..."
                className="pl-9"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>

            <Select
              value={filterProvinsi}
              onValueChange={(val) => {
                setFilterProvinsi(val);
                setFilterKabupaten("all");
              }}
            >
              <SelectTrigger className="w-full sm:w-44">
                <SelectValue placeholder="Provinsi" />
              </SelectTrigger>

              <SelectContent>
                <SelectItem value="all">Semua Provinsi</SelectItem>

                {provinsiList.map((p) => (
                  <SelectItem key={p} value={p}>
                    {p}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select
              value={filterStatus}
              onValueChange={setFilterStatus}
            >
              <SelectTrigger className="w-full sm:w-40">
                <SelectValue placeholder="Status" />
              </SelectTrigger>

              <SelectContent>
                <SelectItem value="all">Semua Status</SelectItem>
                <SelectItem value="Aktif">Aktif</SelectItem>
                <SelectItem value="Tidak Aktif">Tidak Aktif</SelectItem>
                <SelectItem value="Pemantauan">Pemantauan</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Select
              value={filterKabupaten}
              onValueChange={setFilterKabupaten}
            >
              <SelectTrigger className="w-full sm:w-56">
                <SelectValue placeholder="Kabupaten/Kota" />
              </SelectTrigger>

              <SelectContent>
                <SelectItem value="all">Semua Kab/Kota</SelectItem>

                {kabupatenList.map((k) => (
                  <SelectItem key={k} value={k}>
                    {k}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

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

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="w-7 h-7 border-[3px] border-primary/20 border-t-primary rounded-full animate-spin" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-20 text-muted-foreground">
            <Filter className="w-10 h-10 mx-auto mb-3 opacity-40" />
            <p className="text-sm">Belum ada data SPPG</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-primary/5">
                  <TableHead>Nama SPPG</TableHead>
                  <TableHead>Provinsi</TableHead>
                  <TableHead>Kabupaten/Kota</TableHead>
                  <TableHead>Alamat</TableHead>

                  <TableHead className="text-right">
                    Total Dana
                  </TableHead>

                  <TableHead className="text-right">
                    Jumlah Siswa
                  </TableHead>

                  <TableHead>Status</TableHead>

                  <TableHead className="text-center">
                    Aksi
                  </TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                {filtered.map((s) => (
                  <TableRow key={s.id}>
                    <TableCell className="font-medium">
                      {s.nama || "-"}
                    </TableCell>

                    <TableCell>{s.provinsi || "-"}</TableCell>

                    <TableCell>{s.kabupaten || "-"}</TableCell>

                    <TableCell className="max-w-xs truncate">
                      {s.alamat || "-"}
                    </TableCell>

                    <TableCell className="text-right">
                      {formatRp(s.total_dana)}
                    </TableCell>

                    <TableCell className="text-right">
                      {(Number(s.jumlah_siswa) || 0).toLocaleString("id-ID")}
                    </TableCell>

                    <TableCell>
                      <Badge>{s.status || "-"}</Badge>
                    </TableCell>

                    <TableCell className="text-center">
                      <div className="flex items-center justify-center gap-2">
                        <Link to={`/detail-sppg/${s.id}`}>
                          <Button size="sm" variant="ghost">
                            <Eye className="w-4 h-4 mr-1" />
                            Detail
                          </Button>
                        </Link>

                        {isAdmin && (
                          <>
                            <Link to={`/admin/sppg/edit/${s.id}`}>
                              <Button size="sm" variant="outline">
                                <Pencil className="w-4 h-4 mr-1" />
                                Edit
                              </Button>
                            </Link>

                            <Button
                              size="sm"
                              variant="destructive"
                              onClick={() => handleDelete(s.id)}
                            >
                              <Trash2 className="w-4 h-4 mr-1" />
                              Hapus
                            </Button>
                          </>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </div>
    </div>
  );
}