import { useEffect, useState } from "react";
import {
  Users,
  Plus,
  Search,
  Shield,
  Pencil,
  Trash2,
  Save,
  X,
  RefreshCw,
} from "lucide-react";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { createAuditLog } from "../../utils/auditLogger";

const LIST_API = "http://localhost/backend/api/users/list.php";
const CREATE_API = "http://localhost/backend/api/users/create.php";
const UPDATE_API = "http://localhost/backend/api/users/update.php";
const DELETE_API = "http://localhost/backend/api/users/delete.php";

const ROLE_LABELS = {
  admin: "Admin",
  pemerintah: "Pemerintah",
  sppg: "SPPG",
  validator: "Validator",
};

const ROLE_COLORS = {
  admin: "bg-purple-100 text-purple-700",
  pemerintah: "bg-blue-100 text-blue-700",
  sppg: "bg-emerald-100 text-emerald-700",
  validator: "bg-amber-100 text-amber-700",
};

const emptyForm = {
  username: "",
  nama: "",
  email: "",
  password: "",
  role: "sppg",
  status: "Aktif",
};

const formatTanggal = (value) => {
  if (!value) return "Belum pernah login";

  return new Date(value).toLocaleString("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

export default function ManajemenUser() {
  const [search, setSearch] = useState("");
  const [users, setUsers] = useState([]);
  const [showForm, setShowForm] = useState(false);

  const [form, setForm] = useState(emptyForm);
  const [editId, setEditId] = useState(null);
  const [editForm, setEditForm] = useState(emptyForm);

  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [error, setError] = useState("");

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

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

  const filtered = users.filter((u) => {
    const keyword = search.toLowerCase();

    return (
      String(u.username || "").toLowerCase().includes(keyword) ||
      String(u.nama || "").toLowerCase().includes(keyword) ||
      String(u.email || "").toLowerCase().includes(keyword) ||
      String(u.role || "").toLowerCase().includes(keyword) ||
      String(u.status || "").toLowerCase().includes(keyword)
    );
  });

  const handleChange = (setter) => (e) => {
    const { name, value } = e.target;

    setter((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

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

    if (!form.username || !form.nama || !form.email || !form.password) {
      alert("Username, nama, email, dan password wajib diisi.");
      return;
    }

    try {
      setSubmitting(true);

      const res = await fetch(CREATE_API, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: form.username,
          nama: form.nama,
          email: form.email,
          password: form.password,
          role: form.role,
          status: form.status,
        }),
      });

      const result = await res.json();

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

      createAuditLog({
        aksi: "Menambah User",
        target: "Manajemen User",
        keterangan: `Admin menambahkan user ${form.nama} dengan role ${
          ROLE_LABELS[form.role] || form.role
        }.`,
      });

      setForm(emptyForm);
      setShowForm(false);
      await loadUsers();
    } catch (err) {
      console.error("Gagal tambah user:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSubmitting(false);
    }
  };

  const startEdit = (user) => {
    setEditId(user.id);

    setEditForm({
      username: user.username || "",
      nama: user.nama || "",
      email: user.email || "",
      password: "",
      role: user.role || "sppg",
      status: user.status || "Aktif",
    });
  };

  const cancelEdit = () => {
    setEditId(null);
    setEditForm(emptyForm);
  };

  const handleUpdate = async (id) => {
    if (!editForm.username || !editForm.nama || !editForm.email) {
      alert("Username, nama, dan email wajib diisi.");
      return;
    }

    try {
      setUpdating(true);

      const res = await fetch(`${UPDATE_API}?id=${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: editForm.username,
          nama: editForm.nama,
          email: editForm.email,
          password: editForm.password,
          role: editForm.role,
          status: editForm.status,
        }),
      });

      const result = await res.json();

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

      createAuditLog({
        aksi: "Memperbarui User",
        target: "Manajemen User",
        keterangan: `Admin memperbarui data user ${editForm.nama}.`,
      });

      cancelEdit();
      await loadUsers();
    } catch (err) {
      console.error("Gagal update user:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdating(false);
    }
  };

  const handleDelete = async (user) => {
    const yakin = window.confirm(
      `Yakin ingin menghapus user ${user?.nama || user?.username || ""}?`
    );

    if (!yakin) return;

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

      const result = await res.json();

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

      createAuditLog({
        aksi: "Menghapus User",
        target: "Manajemen User",
        keterangan: `Admin menghapus user ${
          user?.nama || user?.username || "-"
        } dari database.`,
      });

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

  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>
          <div className="flex items-center gap-2">
            <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
              <Shield className="w-5 h-5 text-primary" />
            </div>

            <div>
              <h1 className="text-2xl font-black text-foreground">
                Manajemen User
              </h1>
              <p className="text-sm text-muted-foreground mt-1">
                Kelola pengguna, role, dan status akses sistem dari database.
              </p>
            </div>
          </div>
        </div>

        <div className="flex flex-wrap gap-2">
          <Button variant="outline" size="sm" onClick={loadUsers}>
            <RefreshCw className="w-4 h-4 mr-1" />
            Refresh
          </Button>

          <Button
            className="rounded-full bg-primary"
            size="sm"
            onClick={() => setShowForm((prev) => !prev)}
          >
            {showForm ? (
              <>
                <X className="w-4 h-4 mr-1" />
                Tutup Form
              </>
            ) : (
              <>
                <Plus className="w-4 h-4 mr-1" />
                Tambah User
              </>
            )}
          </Button>
        </div>
      </div>

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

      {showForm && (
        <form
          onSubmit={handleTambahUser}
          className="bg-card rounded-xl border border-border p-5 grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-3"
        >
          <Input
            name="username"
            value={form.username}
            onChange={handleChange(setForm)}
            placeholder="Username"
            required
          />

          <Input
            name="nama"
            value={form.nama}
            onChange={handleChange(setForm)}
            placeholder="Nama user"
            required
          />

          <Input
            name="email"
            type="email"
            value={form.email}
            onChange={handleChange(setForm)}
            placeholder="Email user"
            required
          />

          <Input
            name="password"
            type="password"
            value={form.password}
            onChange={handleChange(setForm)}
            placeholder="Password"
            required
          />

          <select
            name="role"
            value={form.role}
            onChange={handleChange(setForm)}
            className="rounded-md border border-input bg-background px-3 py-2 text-sm"
          >
            <option value="admin">Admin</option>
            <option value="pemerintah">Pemerintah</option>
            <option value="sppg">SPPG</option>
            <option value="validator">Validator</option>
          </select>

          <select
            name="status"
            value={form.status}
            onChange={handleChange(setForm)}
            className="rounded-md border border-input bg-background px-3 py-2 text-sm"
          >
            <option value="Aktif">Aktif</option>
            <option value="Tidak Aktif">Tidak Aktif</option>
          </select>

          <div className="md:col-span-3 lg:col-span-6 flex justify-end">
            <Button type="submit" disabled={submitting}>
              <Save className="w-4 h-4 mr-1" />
              {submitting ? "Menyimpan..." : "Simpan User"}
            </Button>
          </div>
        </form>
      )}

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-card rounded-xl border border-border p-4">
          <p className="text-sm text-muted-foreground">Total User</p>
          <p className="text-2xl font-bold mt-1">{users.length}</p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <p className="text-sm text-muted-foreground">Admin</p>
          <p className="text-2xl font-bold mt-1">
            {users.filter((u) => u.role === "admin").length}
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <p className="text-sm text-muted-foreground">User Aktif</p>
          <p className="text-2xl font-bold mt-1">
            {users.filter((u) => u.status === "Aktif").length}
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4">
          <p className="text-sm text-muted-foreground">Tidak Aktif</p>
          <p className="text-2xl font-bold mt-1">
            {users.filter((u) => u.status !== "Aktif").length}
          </p>
        </div>
      </div>

      <div className="relative">
        <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <Input
          placeholder="Cari username, nama, email, role, atau status user..."
          className="pl-10 rounded-xl"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <div className="p-5 border-b border-border flex items-center justify-between">
          <div>
            <h3 className="font-bold text-foreground">Daftar User</h3>
            <p className="text-xs text-muted-foreground mt-1">
              Menampilkan {filtered.length} dari {users.length} user.
            </p>
          </div>
        </div>

        {loading ? (
          <div className="py-12 flex justify-center">
            <div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="py-12 text-center text-sm text-muted-foreground">
            Tidak ada user yang cocok dengan pencarian.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  {[
                    "Username",
                    "Nama",
                    "Email",
                    "Role",
                    "Status",
                    "Login Terakhir",
                    "Aksi",
                  ].map((h) => (
                    <th
                      key={h}
                      className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground"
                    >
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>

              <tbody className="divide-y divide-border">
                {filtered.map((u) => (
                  <tr key={u.id} className="hover:bg-muted/30">
                    {editId === u.id ? (
                      <>
                        <td className="px-4 py-3">
                          <Input
                            name="username"
                            value={editForm.username}
                            onChange={handleChange(setEditForm)}
                            className="h-8"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <Input
                            name="nama"
                            value={editForm.nama}
                            onChange={handleChange(setEditForm)}
                            className="h-8"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <Input
                            name="email"
                            type="email"
                            value={editForm.email}
                            onChange={handleChange(setEditForm)}
                            className="h-8"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <select
                            name="role"
                            value={editForm.role}
                            onChange={handleChange(setEditForm)}
                            className="rounded-md border border-input bg-background px-2 py-1 text-xs"
                          >
                            <option value="admin">Admin</option>
                            <option value="pemerintah">Pemerintah</option>
                            <option value="sppg">SPPG</option>
                            <option value="validator">Validator</option>
                          </select>
                        </td>

                        <td className="px-4 py-3">
                          <select
                            name="status"
                            value={editForm.status}
                            onChange={handleChange(setEditForm)}
                            className="rounded-md border border-input bg-background px-2 py-1 text-xs"
                          >
                            <option value="Aktif">Aktif</option>
                            <option value="Tidak Aktif">Tidak Aktif</option>
                          </select>
                        </td>

                        <td className="px-4 py-3">
                          <Input
                            name="password"
                            type="password"
                            value={editForm.password}
                            onChange={handleChange(setEditForm)}
                            placeholder="Kosongkan jika tidak diganti"
                            className="h-8"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <Button
                              size="sm"
                              className="h-8 text-xs rounded-full"
                              disabled={updating}
                              onClick={() => handleUpdate(u.id)}
                            >
                              <Save className="w-3.5 h-3.5 mr-1" />
                              {updating ? "..." : "Simpan"}
                            </Button>

                            <Button
                              variant="outline"
                              size="sm"
                              className="h-8 text-xs rounded-full"
                              onClick={cancelEdit}
                            >
                              <X className="w-3.5 h-3.5 mr-1" />
                              Batal
                            </Button>
                          </div>
                        </td>
                      </>
                    ) : (
                      <>
                        <td className="px-4 py-3 font-medium">
                          {u.username || "-"}
                        </td>

                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
                              <Users className="w-4 h-4 text-primary" />
                            </div>
                            <span className="font-medium">
                              {u.nama || "-"}
                            </span>
                          </div>
                        </td>

                        <td className="px-4 py-3 text-muted-foreground">
                          {u.email || "-"}
                        </td>

                        <td className="px-4 py-3">
                          <span
                            className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                              ROLE_COLORS[u.role] || "bg-gray-100 text-gray-600"
                            }`}
                          >
                            {ROLE_LABELS[u.role] || u.role || "-"}
                          </span>
                        </td>

                        <td className="px-4 py-3">
                          <span
                            className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                              u.status === "Aktif"
                                ? "bg-emerald-100 text-emerald-700"
                                : "bg-gray-100 text-gray-600"
                            }`}
                          >
                            {u.status || "-"}
                          </span>
                        </td>

                        <td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
                          {formatTanggal(u.last_login)}
                        </td>

                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-8 text-xs rounded-full"
                              onClick={() => startEdit(u)}
                            >
                              <Pencil className="w-3.5 h-3.5 mr-1" />
                              Edit
                            </Button>

                            <Button
                              variant="destructive"
                              size="sm"
                              className="h-8 text-xs rounded-full"
                              onClick={() => handleDelete(u)}
                              disabled={Number(u.id) === 1}
                            >
                              <Trash2 className="w-3.5 h-3.5 mr-1" />
                              Hapus
                            </Button>
                          </div>
                        </td>
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}