"use client";

import type { ReactElement } from "react";

import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { TeamCard } from "@/components/team/TeamCard";
import { ComingSoon } from "@/components/ui/ComingSoon";
import { Button, Input, Modal } from "@mosaic/ui";
import { createTeam, fetchTeams, type CreateTeamDto, type TeamRecord } from "@/lib/api/teams";
import Link from "next/link";

const isDevelopment = process.env.NODE_ENV === "development";

function getErrorMessage(error: unknown, fallback: string): string {
  if (error instanceof Error) {
    return error.message;
  }

  return fallback;
}

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

  const [teams, setTeams] = useState<TeamRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newTeamName, setNewTeamName] = useState("");
  const [newTeamDescription, setNewTeamDescription] = useState("");
  const [createError, setCreateError] = useState<string | null>(null);

  const loadTeams = useCallback(async (): Promise<void> => {
    setIsLoading(true);

    try {
      const data = await fetchTeams(workspaceId);
      setTeams(data);
      setLoadError(null);
    } catch (error) {
      setLoadError(getErrorMessage(error, "Failed to load teams"));
    } finally {
      setIsLoading(false);
    }
  }, [workspaceId]);

  useEffect(() => {
    void loadTeams();
  }, [loadTeams]);

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

    setIsCreating(true);
    setCreateError(null);

    try {
      const description = newTeamDescription.trim();
      const dto: CreateTeamDto = {
        name: teamName,
      };
      if (description.length > 0) {
        dto.description = description;
      }

      await createTeam(dto, workspaceId);

      setNewTeamName("");
      setNewTeamDescription("");
      setShowCreateModal(false);
      await loadTeams();
    } catch (error) {
      setCreateError(getErrorMessage(error, "Failed to create team"));
    } finally {
      setIsCreating(false);
    }
  };

  const teamsForCards = teams.map((team) => ({
    ...team,
    createdAt: new Date(team.createdAt),
    updatedAt: new Date(team.updatedAt),
  }));

  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={() => {
            setCreateError(null);
            setShowCreateModal(true);
          }}
        >
          Create Team
        </Button>
      </div>

      {loadError !== null ? (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-red-700">
          {loadError}
        </div>
      ) : teamsForCards.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={() => {
              setCreateError(null);
              setShowCreateModal(true);
            }}
          >
            Create Team
          </Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {teamsForCards.map((team) => (
            <TeamCard key={team.id} team={team} workspaceId={workspaceId} />
          ))}
        </div>
      )}

      {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: React.ChangeEvent<HTMLInputElement>) => {
                setNewTeamName(e.target.value);
              }}
              placeholder="Enter team name"
              fullWidth
              disabled={isCreating}
              autoFocus
            />
            <Input
              label="Description (optional)"
              value={newTeamDescription}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                setNewTeamDescription(e.target.value);
              }}
              placeholder="Enter team description"
              fullWidth
              disabled={isCreating}
            />
            {createError !== null && (
              <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                {createError}
              </div>
            )}
            <div className="flex gap-2 justify-end pt-4">
              <Button
                variant="ghost"
                onClick={() => {
                  setShowCreateModal(false);
                }}
                disabled={isCreating}
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={() => void handleCreateTeam()}
                disabled={!newTeamName.trim() || isCreating}
              >
                {isCreating ? "Creating..." : "Create Team"}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </main>
  );
}

export default function TeamsPage(): ReactElement {
  if (!isDevelopment) {
    return (
      <ComingSoon
        feature="Team Management"
        description="Organize workspace members into teams for better collaboration. Team management is currently under development."
      >
        <Link href="/settings" className="text-sm text-blue-600 hover:text-blue-700">
          Back to Settings
        </Link>
      </ComingSoon>
    );
  }

  return <TeamsPageContent />;
}
