import { useState, useEffect } from "react";
import type { RegistryItem } from "../lib/types";

const RegistryManager = () => {
  const [registryItems, setRegistryItems] = useState<RegistryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [newItem, setNewItem] = useState({ name: "", link: "" });
  const [showClaimants, setShowClaimants] = useState<Set<string>>(new Set());

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

  const fetchRegistryItems = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/registry");
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setRegistryItems(data);
    } catch (e: any) {
      setError(e.message);
      console.error("Failed to fetch registry items:", e);
    } finally {
      setLoading(false);
    }
  };

  const handleAddItem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newItem.name.trim()) return;

    try {
      const response = await fetch("/api/registry", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newItem),
      });

      if (!response.ok) {
        throw new Error(`Failed to add item: ${response.statusText}`);
      }

      setNewItem({ name: "", link: "" });
      await fetchRegistryItems();
    } catch (error: any) {
      setError(error.message);
      console.error("Error adding item:", error);
    }
  };

  const handleDeleteItem = async (itemId: string) => {
    if (!confirm("Are you sure you want to delete this item?")) return;

    try {
      const response = await fetch(`/api/registry/${itemId}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        throw new Error(`Failed to delete item: ${response.statusText}`);
      }

      await fetchRegistryItems();
    } catch (error: any) {
      setError(error.message);
      console.error("Error deleting item:", error);
    }
  };

  const toggleClaimantVisibility = (itemId: string) => {
    const newShowClaimants = new Set(showClaimants);
    if (newShowClaimants.has(itemId)) {
      newShowClaimants.delete(itemId);
    } else {
      newShowClaimants.add(itemId);
    }
    setShowClaimants(newShowClaimants);
  };

  if (loading) {
    return <div className="text-center">Loading registry items...</div>;
  }

  if (error) {
    return <div className="text-red-500 text-center">Error: {error}</div>;
  }

  return (
    <div className="container mx-auto p-4">
      <form onSubmit={handleAddItem} className="mb-8">
        <div className="card bg-base-100 shadow-xl">
          <div className="card-body">
            <h2 className="card-title">Add New Item</h2>
            <div className="form-control">
              <label className="label">
                <span className="label-text">Item Name</span>
              </label>
              <input
                type="text"
                placeholder="Enter item name"
                className="input input-bordered"
                value={newItem.name}
                onChange={(e) =>
                  setNewItem({ ...newItem, name: e.target.value })
                }
                required
              />
            </div>
            <div className="form-control">
              <label className="label">
                <span className="label-text">Item Link (optional)</span>
              </label>
              <input
                type="url"
                placeholder="Enter item link"
                className="input input-bordered"
                value={newItem.link}
                onChange={(e) =>
                  setNewItem({ ...newItem, link: e.target.value })
                }
              />
            </div>
            <div className="card-actions justify-end">
              <button type="submit" className="btn btn-primary">
                Add Item
              </button>
            </div>
          </div>
        </div>
      </form>

      <div className="overflow-x-auto">
        <table className="table w-full">
          <thead>
            <tr>
              <th>Item</th>
              <th>Link</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {registryItems.map((item) => (
              <tr key={item.id}>
                <td>
                  <div className="flex items-center gap-2">
                    {item.name}
                    {item.taken && (
                      <>
                        <span className="badge badge-success">Taken</span>
                        {item.claimedBy && (
                          <button
                            onClick={() => toggleClaimantVisibility(item.id)}
                            className="btn btn-ghost btn-xs"
                          >
                            {showClaimants.has(item.id) ? (
                              <i className="fas fa-eye-slash" />
                            ) : (
                              <i className="fas fa-eye" />
                            )}
                          </button>
                        )}
                      </>
                    )}
                  </div>
                  {item.taken &&
                    item.claimedBy &&
                    showClaimants.has(item.id) && (
                      <div className="text-sm text-gray-500">
                        Claimed by: {item.claimedBy}
                      </div>
                    )}
                </td>
                <td>
                  {item.link && (
                    <a
                      href={item.link}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="link link-primary"
                    >
                      View
                    </a>
                  )}
                </td>
                <td>{item.taken ? "Claimed" : "Available"}</td>
                <td>
                  <button
                    className="btn btn-error btn-sm"
                    onClick={() => handleDeleteItem(item.id)}
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default RegistryManager;
