'use client';

import { useState } from 'react';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { SprintDetails } from '../SprintDetailModal';
import { formatDateForDisplay } from '@/lib/date-utils';

interface SprintIssuesProps {
  sprintDetails: SprintDetails;
}

export function SprintIssues({ sprintDetails }: SprintIssuesProps) {
  const { issues, assigneeDistribution, statusDistribution } = sprintDetails;
  const [selectedAssignee, setSelectedAssignee] = useState<string | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<string | null>(null);

  const getStatusColor = (status: string): string => {
    if (
      status.toLowerCase().includes('done') ||
      status.toLowerCase().includes('closed')
    ) {
      return 'bg-green-100 text-green-800';
    }
    if (
      status.toLowerCase().includes('progress') ||
      status.toLowerCase().includes('review')
    ) {
      return 'bg-blue-100 text-blue-800';
    }
    if (
      status.toLowerCase().includes('blocked') ||
      status.toLowerCase().includes('waiting')
    ) {
      return 'bg-red-100 text-red-800';
    }
    return 'bg-gray-100 text-gray-800';
  };

  const getPriorityColor = (priority: string): string => {
    switch (priority?.toLowerCase()) {
      case 'highest':
      case 'critical':
        return 'bg-red-100 text-red-800';
      case 'high':
        return 'bg-orange-100 text-orange-800';
      case 'medium':
        return 'bg-yellow-100 text-yellow-800';
      case 'low':
        return 'bg-green-100 text-green-800';
      case 'lowest':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // Filtrer les issues selon les sélections
  const filteredIssues = issues.filter((issue) => {
    if (
      selectedAssignee &&
      (issue.assignee?.displayName || 'Non assigné') !== selectedAssignee
    ) {
      return false;
    }
    if (selectedStatus && issue.status.name !== selectedStatus) {
      return false;
    }
    return true;
  });

  return (
    <div className="space-y-4">
      {/* Filtres */}
      <Card>
        <CardHeader>
          <h3 className="font-semibold">🔍 Filtres</h3>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {/* Filtre par assigné */}
            <div className="flex flex-wrap gap-1">
              <Button
                variant={selectedAssignee === null ? 'primary' : 'ghost'}
                size="sm"
                onClick={() => setSelectedAssignee(null)}
              >
                Tous les assignés
              </Button>
              {assigneeDistribution.map((assignee, index) => (
                <Button
                  key={index}
                  variant={
                    selectedAssignee === (assignee.assignee || 'Non assigné')
                      ? 'primary'
                      : 'ghost'
                  }
                  size="sm"
                  onClick={() =>
                    setSelectedAssignee(assignee.assignee || 'Non assigné')
                  }
                >
                  {assignee.assignee || 'Non assigné'} (
                  {assignee.count || assignee.totalIssues})
                </Button>
              ))}
            </div>

            {/* Filtre par statut */}
            <div className="flex flex-wrap gap-1 mt-2">
              <Button
                variant={selectedStatus === null ? 'primary' : 'ghost'}
                size="sm"
                onClick={() => setSelectedStatus(null)}
              >
                Tous les statuts
              </Button>
              {statusDistribution.map((status, index) => (
                <Button
                  key={index}
                  variant={
                    selectedStatus === status.status ? 'primary' : 'ghost'
                  }
                  size="sm"
                  onClick={() => setSelectedStatus(status.status)}
                >
                  {status.status} ({status.count})
                </Button>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Liste des issues */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <h3 className="font-semibold">
              📝 Issues ({filteredIssues.length})
            </h3>
            {(selectedAssignee || selectedStatus) && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setSelectedAssignee(null);
                  setSelectedStatus(null);
                }}
              >
                Réinitialiser filtres
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {filteredIssues.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              Aucune issue ne correspond aux filtres sélectionnés
            </div>
          ) : (
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {filteredIssues.map((issue) => (
                <div
                  key={issue.key}
                  className="border border-gray-200 rounded-lg p-3 hover:bg-gray-50 transition-colors"
                >
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-mono text-sm text-blue-600">
                          {issue.key}
                        </span>
                        <Badge
                          className={getPriorityColor(
                            issue.priority?.name || ''
                          )}
                          size="sm"
                        >
                          {issue.priority?.name || 'No Priority'}
                        </Badge>
                      </div>
                      <h4 className="font-medium text-sm mb-1 line-clamp-2">
                        {issue.summary}
                      </h4>
                    </div>
                    <Badge
                      className={getStatusColor(issue.status.name)}
                      size="sm"
                    >
                      {issue.status.name}
                    </Badge>
                  </div>

                  <div className="flex items-center justify-between text-xs text-gray-600">
                    <div className="flex items-center gap-4">
                      <span>
                        👤 {issue.assignee?.displayName || 'Non assigné'}
                      </span>
                      <span>
                        📊{' '}
                        {issue.issueType?.name ||
                          issue.issuetype?.name ||
                          'N/A'}
                      </span>
                      {issue.storyPoints && (
                        <span>🎯 {issue.storyPoints} pts</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      {issue.created && (
                        <span>
                          📅 {formatDateForDisplay(new Date(issue.created))}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
