import { useState, useEffect } from "react";
import type { RegistryItem } from "../lib/types";
import { fetchWithAuth, getAuthToken } from "../utils/auth-client";

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());

  const fetchRegistryItems = async () => {
    // Don't try to fetch if we don't have a token yet
    if (!getAuthToken()) {
      setError("No authentication token found");
      setLoading(false);
      return;
    }

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

  useEffect(() => {
    fetchRegistryItems();

    // Add listener for auth success to retry fetching
    const handleAuthSuccess = () => {
      fetchRegistryItems();
    };
    document.addEventListener("auth-success", handleAuthSuccess);
    return () => document.removeEventListener("auth-success", handleAuthSuccess);
  }, []);

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

    try {
      const response = await fetchWithAuth("/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 (id: string) => {
    try {
      const response = await fetchWithAuth(`/api/registry/${id}`, {
        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 handleReleaseClaim = async (id: string) => {
    try {
      const response = await fetchWithAuth(`/api/registry/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ taken: false, claimedBy: null }),
      });

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

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

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

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

  if (error) {
    if (error === "No authentication token found") {
      return <div className="text-center">Initializing...</div>;
    }
    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 max-w-2xl mx-auto">
        <div className="grid grid-cols-1 gap-4">
          <div className="form-control w-full">
            <input
              type="text"
              value={newItem.name}
              onChange={(e) => setNewItem({ ...newItem, name: e.target.value })}
              placeholder="Item name"
              className="input input-bordered w-full"
              required
            />
          </div>
          <div className="form-control w-full">
            <input
              type="url"
              value={newItem.link}
              onChange={(e) => setNewItem({ ...newItem, link: e.target.value })}
              placeholder="Item link (optional)"
              className="input input-bordered w-full"
            />
          </div>
          <div className="form-control w-full">
            <button type="submit" className="btn btn-primary w-full">
              Add Item
            </button>
          </div>
        </div>
      </form>

      <div className="overflow-x-auto">
        <table className="table w-full">
          <thead>
            <tr>
              <th>Name</th>
              <th>Link</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {registryItems.map((item) => (
              <tr key={item.id}>
                <td>{item.name}</td>
                <td>
                  {item.link && (
                    <a
                      href={item.link}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="link link-primary"
                    >
                      View Item
                    </a>
                  )}
                </td>
                <td>
                  <div className="flex items-center gap-2">
                    <span
                      className={`badge ${
                        item.taken ? "badge-error" : "badge-success"
                      }`}
                    >
                      {item.taken ? "Claimed" : "Available"}
                    </span>
                    {item.taken && (
                      <button
                        onClick={() => toggleShowClaimant(item.id)}
                        className="btn btn-xs"
                      >
                        {showClaimants.has(item.id) ? "Hide" : "Show"} Claimant
                      </button>
                    )}
                  </div>
                  {item.taken && showClaimants.has(item.id) && (
                    <div className="text-sm mt-1">
                      Claimed by: {item.claimedBy}
                    </div>
                  )}
                </td>
                <td>
                  <div className="flex gap-2">
                    {item.taken && (
                      <button
                        onClick={() => handleReleaseClaim(item.id)}
                        className="btn btn-warning btn-sm"
                      >
                        Release Claim
                      </button>
                    )}
                    <button
                      onClick={() => handleDeleteItem(item.id)}
                      className="btn btn-error btn-sm"
                    >
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default RegistryManager;
