"use client";

import { useState, useEffect, useCallback } from "react";
import { useConfirm } from "@/components/shared/use-confirm";

interface OptionItem {
  id: number;
  name: string;
  slug?: string;
  [key: string]: unknown;
}

interface OptionCrudPageProps {
  title: string;
  apiEndpoint: string;
  columns?: string[];
}

export function OptionCrudPage({ title, apiEndpoint, columns = ["name"] }: OptionCrudPageProps) {
  const [items, setItems] = useState<OptionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [newItem, setNewItem] = useState("");
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editValue, setEditValue] = useState("");
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  const fetchItems = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(apiEndpoint);
      const data = await res.json();
      setItems(Array.isArray(data) ? data : data.data || []);
    } catch (err) {
      console.error("Failed to fetch items:", err);
    } finally {
      setLoading(false);
    }
  }, [apiEndpoint]);

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

  async function handleCreate() {
    if (!newItem.trim()) return;
    try {
      // B.9: previously this swallowed non-OK responses (validation errors,
      // 409 conflict on duplicate name) and silently appeared to refresh.
      const res = await fetch(apiEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newItem }),
      });
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        alert(`Create failed: ${text || res.status}`);
        return;
      }
      setNewItem("");
      fetchItems();
    } catch (err) {
      console.error("Failed to create:", err);
      alert("Create failed: network error");
    }
  }

  async function handleUpdate(id: number) {
    try {
      const res = await fetch(`${apiEndpoint}/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: editValue }),
      });
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        alert(`Update failed: ${text || res.status}`);
        return;
      }
      setEditingId(null);
      fetchItems();
    } catch (err) {
      console.error("Failed to update:", err);
      alert("Update failed: network error");
    }
  }

  async function handleDelete(id: number) {
    if (!(await askConfirm({ title: "Delete item", message: "Are you sure?" }))) return;
    try {
      await fetch(`${apiEndpoint}/${id}`, { method: "DELETE" });
      fetchItems();
    } catch (err) {
      console.error("Failed to delete:", err);
    }
  }

  return (
    <div>
      {confirmDialog}
      <h1 className="text-2xl font-bold mb-6">{title}</h1>

      {/* Create form */}
      <div className="flex gap-2 mb-6">
        <input
          type="text"
          value={newItem}
          onChange={(e) => setNewItem(e.target.value)}
          placeholder={`New ${title.toLowerCase().replace(/s$/, "")}...`}
          className="flex-1 px-3 py-2 bg-surface-light border border-surface-light rounded-lg text-text focus:outline-none focus:ring-2 focus:ring-primary"
          onKeyDown={(e) => e.key === "Enter" && handleCreate()}
        />
        <button
          onClick={handleCreate}
          className="px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-colors"
        >
          Add
        </button>
      </div>

      {/* Table */}
      {loading ? (
        <div className="text-text-muted">Loading...</div>
      ) : (
        <table className="w-full">
          <thead>
            <tr className="border-b border-surface-light">
              <th className="text-left py-3 px-4 text-text-muted text-sm">ID</th>
              {columns.map((col) => (
                <th key={col} className="text-left py-3 px-4 text-text-muted text-sm capitalize">
                  {col}
                </th>
              ))}
              <th className="text-right py-3 px-4 text-text-muted text-sm">Actions</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item) => (
              <tr key={item.id} className="border-b border-surface-light hover:bg-surface-light/50">
                <td className="py-3 px-4 text-text-muted">{item.id}</td>
                {columns.map((col) => (
                  <td key={col} className="py-3 px-4">
                    {editingId === item.id ? (
                      <input
                        type="text"
                        value={editValue}
                        onChange={(e) => setEditValue(e.target.value)}
                        className="px-2 py-1 bg-surface-light border border-surface-light rounded text-text focus:outline-none focus:ring-1 focus:ring-primary"
                        onKeyDown={(e) => e.key === "Enter" && handleUpdate(item.id)}
                      />
                    ) : (
                      String(item[col] ?? "")
                    )}
                  </td>
                ))}
                <td className="py-3 px-4 text-right space-x-2">
                  {editingId === item.id ? (
                    <>
                      <button
                        onClick={() => handleUpdate(item.id)}
                        className="text-green-400 hover:text-green-300 text-sm"
                      >
                        Save
                      </button>
                      <button
                        onClick={() => setEditingId(null)}
                        className="text-text-muted hover:text-white text-sm"
                      >
                        Cancel
                      </button>
                    </>
                  ) : (
                    <>
                      <button
                        onClick={() => { setEditingId(item.id); setEditValue(String(item.name)); }}
                        className="text-primary hover:text-primary-light text-sm"
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => handleDelete(item.id)}
                        className="text-red-400 hover:text-red-300 text-sm"
                      >
                        Delete
                      </button>
                    </>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {items.length === 0 && !loading && (
        <div className="text-center py-8 text-text-muted">
          No items yet. Add one above.
        </div>
      )}
    </div>
  );
}
