'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  SprintVelocity,
  JiraTask,
  AssigneeDistribution,
  StatusDistribution,
} from '@/lib/types';
import { Modal } from '@/components/ui/Modal';
import { Button } from '@/components/ui/Button';
import { SprintOverview } from './sprint/SprintOverview';
import { SprintIssues } from './sprint/SprintIssues';
import { SprintMetrics } from './sprint/SprintMetrics';

interface SprintDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  sprint: SprintVelocity | null;
  onLoadSprintDetails: (sprintName: string) => Promise<SprintDetails>;
}

export interface SprintDetails {
  sprint: SprintVelocity;
  issues: JiraTask[];
  assigneeDistribution: AssigneeDistribution[];
  statusDistribution: StatusDistribution[];
  metrics: {
    totalIssues: number;
    completedIssues: number;
    inProgressIssues: number;
    blockedIssues: number;
    averageCycleTime: number;
    velocityTrend: 'up' | 'down' | 'stable';
  };
}

export default function SprintDetailModal({
  isOpen,
  onClose,
  sprint,
  onLoadSprintDetails,
}: SprintDetailModalProps) {
  const [sprintDetails, setSprintDetails] = useState<SprintDetails | null>(
    null
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedTab, setSelectedTab] = useState<
    'overview' | 'issues' | 'metrics'
  >('overview');

  const loadSprintDetails = useCallback(async () => {
    if (!sprint) return;

    setLoading(true);
    setError(null);

    try {
      const details = await onLoadSprintDetails(sprint.sprintName);
      setSprintDetails(details);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Erreur lors du chargement'
      );
    } finally {
      setLoading(false);
    }
  }, [sprint, onLoadSprintDetails]);

  // Charger les détails du sprint quand le modal s'ouvre
  useEffect(() => {
    if (isOpen && sprint && !sprintDetails) {
      loadSprintDetails();
    }
  }, [isOpen, sprint, sprintDetails, loadSprintDetails]);

  // Reset quand on change de sprint
  useEffect(() => {
    if (sprint) {
      setSprintDetails(null);
      setSelectedTab('overview');
    }
  }, [sprint]);

  if (!sprint) return null;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={`Sprint: ${sprint.sprintName}`}
      size="xl"
    >
      <div className="space-y-4">
        {/* Navigation par onglets */}
        <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg">
          <Button
            variant={selectedTab === 'overview' ? 'primary' : 'ghost'}
            size="sm"
            onClick={() => setSelectedTab('overview')}
            className="flex-1"
          >
            📋 Vue d&apos;ensemble
          </Button>
          <Button
            variant={selectedTab === 'issues' ? 'primary' : 'ghost'}
            size="sm"
            onClick={() => setSelectedTab('issues')}
            className="flex-1"
          >
            📝 Issues
          </Button>
          <Button
            variant={selectedTab === 'metrics' ? 'primary' : 'ghost'}
            size="sm"
            onClick={() => setSelectedTab('metrics')}
            className="flex-1"
          >
            📊 Métriques
          </Button>
        </div>

        {/* Contenu des onglets */}
        <div className="min-h-[500px] max-h-[70vh] overflow-y-auto">
          {loading && (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
                <p className="text-gray-600">
                  Chargement des détails du sprint...
                </p>
              </div>
            </div>
          )}

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-center">
              <p className="text-red-700 mb-2">❌ {error}</p>
              <Button onClick={loadSprintDetails} variant="secondary" size="sm">
                🔄 Réessayer
              </Button>
            </div>
          )}

          {!loading && !error && sprintDetails && (
            <>
              {selectedTab === 'overview' && (
                <SprintOverview sprintDetails={sprintDetails} />
              )}
              {selectedTab === 'issues' && (
                <SprintIssues sprintDetails={sprintDetails} />
              )}
              {selectedTab === 'metrics' && (
                <SprintMetrics sprintDetails={sprintDetails} />
              )}
            </>
          )}

          {!loading && !error && !sprintDetails && (
            <div className="text-center py-12 text-gray-500">
              <p>Aucun détail disponible pour ce sprint</p>
              <Button
                onClick={loadSprintDetails}
                variant="primary"
                size="sm"
                className="mt-2"
              >
                📊 Charger les détails
              </Button>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}
