"use client";

import type { ReactElement } from "react";

import { useState } from "react";
import { useParams } from "next/navigation";
import { TeamCard } from "@/components/team/TeamCard";
import { Button, Input, Modal } from "@mosaic/ui";
import { mockTeams } from "@/lib/api/teams";

export default function TeamsPage(): ReactElement {
  const params = useParams();
  const workspaceId = params.id as string;

  // TODO: Replace with real API call when backend is ready
  // const { data: teams, isLoading } = useQuery({
  //   queryKey: ["teams", workspaceId],
  //   queryFn: () => fetchTeams(workspaceId),
  // });

  const [teams] = useState(mockTeams);
  const [isLoading] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newTeamName, setNewTeamName] = useState("");
  const [newTeamDescription, setNewTeamDescription] = useState("");

  const handleCreateTeam = (): void => {
    if (!newTeamName.trim()) return;

    setIsCreating(true);
    try {
      // TODO: Replace with real API call
      // await createTeam(workspaceId, {
      //   name: newTeamName,
      //   description: newTeamDescription || undefined,
      // });

      console.log("Creating team:", { name: newTeamName, description: newTeamDescription });

      // Reset form
      setNewTeamName("");
      setNewTeamDescription("");
      setShowCreateModal(false);

      // TODO: Refresh teams list
    } catch (_error) {
      console.error("Failed to create team:", _error);
      alert("Failed to create team. Please try again.");
    } finally {
      setIsCreating(false);
    }
  };

  if (isLoading) {
    return (
      <main className="container mx-auto px-4 py-8">
        <div className="flex justify-center items-center p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
          <span className="ml-3 text-gray-600">Loading teams...</span>
        </div>
      </main>
    );
  }

  return (
    <main className="container mx-auto px-4 py-8">
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Teams</h1>
          <p className="text-gray-600 mt-2">Organize workspace members into teams</p>
        </div>
        <Button
          variant="primary"
          onClick={() => {
            setShowCreateModal(true);
          }}
        >
          Create Team
        </Button>
      </div>

      {teams.length === 0 ? (
        <div className="text-center p-12 bg-gray-50 rounded-lg">
          <p className="text-lg text-gray-500 mb-4">No teams yet</p>
          <p className="text-sm text-gray-400 mb-6">
            Create your first team to organize workspace members
          </p>
          <Button
            variant="primary"
            onClick={() => {
              setShowCreateModal(true);
            }}
          >
            Create Team
          </Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {teams.map((team) => (
            <TeamCard key={team.id} team={team} workspaceId={workspaceId} />
          ))}
        </div>
      )}

      {/* Create Team Modal */}
      {showCreateModal && (
        <Modal
          isOpen={showCreateModal}
          onClose={() => {
            if (!isCreating) {
              setShowCreateModal(false);
            }
          }}
          title="Create New Team"
        >
          <div className="space-y-4">
            <Input
              label="Team Name"
              value={newTeamName}
              onChange={(e) => {
                setNewTeamName(e.target.value);
              }}
              placeholder="Enter team name"
              fullWidth
              disabled={isCreating}
              autoFocus
            />
            <Input
              label="Description (optional)"
              value={newTeamDescription}
              onChange={(e) => {
                setNewTeamDescription(e.target.value);
              }}
              placeholder="Enter team description"
              fullWidth
              disabled={isCreating}
            />
            <div className="flex gap-2 justify-end pt-4">
              <Button
                variant="ghost"
                onClick={() => {
                  setShowCreateModal(false);
                }}
                disabled={isCreating}
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={handleCreateTeam}
                disabled={!newTeamName.trim() || isCreating}
              >
                {isCreating ? "Creating..." : "Create Team"}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </main>
  );
}
