'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import DataWarning from '@/components/alpha/DataWarning';
import Breadcrumbs from '@/components/alpha/Breadcrumbs';
import TeamRoster from '@/components/alpha/TeamRoster';
import TeamStandings from '@/components/alpha/TeamStandings';
import TeamAdmin from '@/components/alpha/TeamAdmin';
import JoinTeamButton from '@/components/alpha/JoinTeamButton';
import {
  Team,
  getTeam,
  getTeamMembers,
  getCurrentDriverId,
  isTeamOwnerOrManager,
  TeamMembership,
  removeTeamMember,
  updateTeamMemberRole,
  TeamRole,
} from '@/lib/team-data';

type Tab = 'overview' | 'roster' | 'standings' | 'admin';

export default function TeamDetailPage() {
  const params = useParams();
  const teamId = params.id as string;
  
  const [team, setTeam] = useState<Team | null>(null);
  const [memberships, setMemberships] = useState<TeamMembership[]>([]);
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);

  const loadTeamData = () => {
    const teamData = getTeam(teamId);
    if (!teamData) {
      setLoading(false);
      return;
    }

    const teamMemberships = getTeamMembers(teamId);
    const currentDriverId = getCurrentDriverId();
    const adminStatus = isTeamOwnerOrManager(teamId, currentDriverId);

    setTeam(teamData);
    setMemberships(teamMemberships);
    setIsAdmin(adminStatus);
    setLoading(false);
  };

  useEffect(() => {
    loadTeamData();
  }, [teamId]);

  const handleUpdate = () => {
    loadTeamData();
  };

  const handleRemoveMember = (driverId: string) => {
    if (!confirm('Are you sure you want to remove this member?')) {
      return;
    }

    try {
      const currentDriverId = getCurrentDriverId();
      removeTeamMember(teamId, driverId, currentDriverId);
      handleUpdate();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to remove member');
    }
  };

  const handleChangeRole = (driverId: string, newRole: TeamRole) => {
    try {
      const currentDriverId = getCurrentDriverId();
      updateTeamMemberRole(teamId, driverId, newRole, currentDriverId);
      handleUpdate();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to change role');
    }
  };

  if (loading) {
    return (
      <div className="max-w-6xl mx-auto">
        <div className="text-center text-gray-400">Loading team...</div>
      </div>
    );
  }

  if (!team) {
    return (
      <div className="max-w-6xl mx-auto">
        <Card>
          <div className="text-center py-12">
            <h2 className="text-2xl font-bold text-white mb-2">Team Not Found</h2>
            <p className="text-gray-400 mb-6">
              The team you're looking for doesn't exist or has been disbanded.
            </p>
            <Button variant="primary" onClick={() => window.history.back()}>
              Go Back
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  const tabs: { id: Tab; label: string; visible: boolean }[] = [
    { id: 'overview', label: 'Overview', visible: true },
    { id: 'roster', label: 'Roster', visible: true },
    { id: 'standings', label: 'Standings', visible: true },
    { id: 'admin', label: 'Admin', visible: isAdmin },
  ];

  const visibleTabs = tabs.filter(tab => tab.visible);

  return (
    <div className="max-w-6xl mx-auto">
      {/* Breadcrumb */}
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          { label: 'Teams', href: '/teams' },
          { label: team.name }
        ]}
      />

      <DataWarning className="mb-6" />

      <Card className="mb-6">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-6">
            <div className="w-24 h-24 bg-charcoal-outline rounded-lg flex items-center justify-center flex-shrink-0">
              <span className="text-4xl font-bold text-gray-500">
                {team.tag}
              </span>
            </div>
            
            <div>
              <div className="flex items-center gap-3 mb-2">
                <h1 className="text-3xl font-bold text-white">{team.name}</h1>
                <span className="px-3 py-1 bg-charcoal-outline text-gray-300 rounded-full text-sm font-medium">
                  {team.tag}
                </span>
              </div>
              
              <p className="text-gray-300 mb-4 max-w-2xl">{team.description}</p>
              
              <div className="flex items-center gap-4 text-sm text-gray-400">
                <span>{memberships.length} {memberships.length === 1 ? 'member' : 'members'}</span>
                <span>•</span>
                <span>Created {new Date(team.createdAt).toLocaleDateString()}</span>
                {team.leagues.length > 0 && (
                  <>
                    <span>•</span>
                    <span>{team.leagues.length} {team.leagues.length === 1 ? 'league' : 'leagues'}</span>
                  </>
                )}
              </div>
            </div>
          </div>

          <JoinTeamButton teamId={teamId} onUpdate={handleUpdate} />
        </div>
      </Card>

      <div className="mb-6">
        <div className="flex items-center gap-2 border-b border-charcoal-outline">
          {visibleTabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                px-4 py-3 font-medium transition-all relative
                ${activeTab === tab.id 
                  ? 'text-primary-blue' 
                  : 'text-gray-400 hover:text-white'
                }
              `}
            >
              {tab.label}
              {activeTab === tab.id && (
                <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary-blue" />
              )}
            </button>
          ))}
        </div>
      </div>

      <div>
        {activeTab === 'overview' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <Card className="lg:col-span-2">
                <h3 className="text-xl font-semibold text-white mb-4">About</h3>
                <p className="text-gray-300 leading-relaxed">{team.description}</p>
              </Card>

              <Card>
                <h3 className="text-xl font-semibold text-white mb-4">Quick Stats</h3>
                <div className="space-y-3">
                  <StatItem label="Members" value={memberships.length.toString()} color="text-primary-blue" />
                  <StatItem label="Leagues" value={team.leagues.length.toString()} color="text-green-400" />
                  <StatItem label="Founded" value={new Date(team.createdAt).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })} color="text-gray-300" />
                </div>
              </Card>
            </div>

            <Card>
              <h3 className="text-xl font-semibold text-white mb-4">Recent Activity</h3>
              <div className="text-center py-8 text-gray-400">
                No recent activity to display
              </div>
            </Card>
          </div>
        )}

        {activeTab === 'roster' && (
          <TeamRoster
            teamId={teamId}
            memberships={memberships}
            isAdmin={isAdmin}
            onRemoveMember={handleRemoveMember}
            onChangeRole={handleChangeRole}
          />
        )}

        {activeTab === 'standings' && (
          <TeamStandings teamId={teamId} leagues={team.leagues} />
        )}

        {activeTab === 'admin' && isAdmin && (
          <TeamAdmin team={team} onUpdate={handleUpdate} />
        )}
      </div>
    </div>
  );
}

function StatItem({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-gray-400 text-sm">{label}</span>
      <span className={`font-semibold ${color}`}>{value}</span>
    </div>
  );
}