/**
 * Composant pour afficher l'historique des versions d'une playlist
 * T0509: Create Playlist Version History
 */

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog } from '@/components/ui/dialog';
import { History, RotateCcw, Loader2, Calendar, User } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
import type { Playlist } from '../types';

export interface PlaylistVersion {
  id: number;
  playlist_id: number;
  user_id: number;
  version: number;
  action: 'created' | 'updated' | 'restored';
  title: string;
  description?: string;
  is_public: boolean;
  cover_url?: string;
  tracks_snapshot?: string;
  created_at: string;
  user?: {
    id: number;
    username: string;
  };
}

interface PlaylistVersionHistoryProps {
  playlistId: number;
  canRestore?: boolean;
  className?: string;
}

/**
 * Formate la date pour l'affichage
 */
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('fr-FR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(date);
}

/**
 * Obtient le label de l'action
 */
function getActionLabel(action: string): string {
  switch (action) {
    case 'created':
      return 'Créée';
    case 'updated':
      return 'Modifiée';
    case 'restored':
      return 'Restaurée';
    default:
      return action;
  }
}

/**
 * Obtient la couleur de l'action
 */
function getActionColor(action: string): string {
  switch (action) {
    case 'created':
      return 'text-green-600 dark:text-green-400';
    case 'updated':
      return 'text-blue-600 dark:text-blue-400';
    case 'restored':
      return 'text-purple-600 dark:text-purple-400';
    default:
      return 'text-gray-600 dark:text-gray-400';
  }
}

export function PlaylistVersionHistory({
  playlistId,
  canRestore = false,
  className,
}: PlaylistVersionHistoryProps) {
  const [showHistory, setShowHistory] = useState(false);
  const [restoreVersion, setRestoreVersion] = useState<number | null>(null);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Récupérer l'historique des versions
  const { data, isLoading, error } = useQuery<{
    versions: PlaylistVersion[];
    total: number;
    limit: number;
    offset: number;
  }>({
    queryKey: ['playlist-versions', playlistId],
    queryFn: async () => {
      const response = await apiClient.get(`/api/v1/playlists/${playlistId}/versions`);
      return response.data;
    },
    enabled: showHistory,
  });

  // Mutation pour restaurer une version
  const restoreMutation = useMutation({
    mutationFn: async (version: number) => {
      const response = await apiClient.post(
        `/api/v1/playlists/${playlistId}/versions/${version}/restore`
      );
      return response.data;
    },
    onSuccess: () => {
      toast({
        title: 'Version restaurée',
        description: 'La playlist a été restaurée avec succès.',
      });
      setRestoreVersion(null);
      setShowHistory(false);
      // Invalider les caches pour rafraîchir les données
      queryClient.invalidateQueries({ queryKey: ['playlist', playlistId] });
      queryClient.invalidateQueries({ queryKey: ['playlist-versions', playlistId] });
    },
    onError: (error: any) => {
      toast({
        title: 'Erreur',
        description: error?.response?.data?.error || 'Erreur lors de la restauration',
        variant: 'destructive',
      });
    },
  });

  const handleRestore = () => {
    if (restoreVersion !== null) {
      restoreMutation.mutate(restoreVersion);
    }
  };

  return (
    <>
      <Button
        variant="outline"
        size="sm"
        onClick={() => setShowHistory(true)}
        className={cn('touch-manipulation min-h-[44px] sm:min-h-0', className)}
        aria-label="Voir l'historique des versions"
      >
        <History className="w-4 h-4 sm:mr-2" aria-hidden="true" />
        <span className="hidden sm:inline">Historique</span>
      </Button>

      <Dialog
        open={showHistory}
        onClose={() => {
          setShowHistory(false);
          setRestoreVersion(null);
        }}
        title="Historique des versions"
        size="lg"
        aria-label="Dialogue d'historique des versions"
      >
        <div className="space-y-4">
          {isLoading && (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              <span className="ml-2 text-muted-foreground">Chargement de l'historique...</span>
            </div>
          )}

          {error && (
            <div className="text-center py-8">
              <p className="text-destructive">Erreur lors du chargement de l'historique</p>
            </div>
          )}

          {data && data.versions.length === 0 && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">Aucune version disponible</p>
            </div>
          )}

          {data && data.versions.length > 0 && (
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {data.versions.map((version) => (
                <Card
                  key={version.id}
                  className={cn(
                    'transition-all',
                    restoreVersion === version.version && 'ring-2 ring-blue-500'
                  )}
                >
                  <CardContent className="p-4">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 space-y-2">
                        <div className="flex items-center gap-2">
                          <span className="font-semibold text-lg">Version {version.version}</span>
                          <span
                            className={cn(
                              'text-xs px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-800',
                              getActionColor(version.action)
                            )}
                          >
                            {getActionLabel(version.action)}
                          </span>
                        </div>

                        <div className="space-y-1 text-sm text-muted-foreground">
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4" aria-hidden="true" />
                            <span>{formatDate(version.created_at)}</span>
                          </div>
                          {version.user && (
                            <div className="flex items-center gap-2">
                              <User className="w-4 h-4" aria-hidden="true" />
                              <span>{version.user.username}</span>
                            </div>
                          )}
                        </div>

                        {version.title && (
                          <div className="pt-2">
                            <p className="font-medium">{version.title}</p>
                            {version.description && (
                              <p className="text-sm text-muted-foreground line-clamp-2">
                                {version.description}
                              </p>
                            )}
                          </div>
                        )}
                      </div>

                      {canRestore && version.action !== 'restored' && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setRestoreVersion(version.version)}
                          className="touch-manipulation min-h-[44px] sm:min-h-0"
                          aria-label={`Restaurer la version ${version.version}`}
                        >
                          <RotateCcw className="w-4 h-4 sm:mr-2" aria-hidden="true" />
                          <span className="hidden sm:inline">Restaurer</span>
                        </Button>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          {restoreVersion !== null && (
            <div className="pt-4 border-t">
              <div className="flex items-center justify-between gap-4">
                <p className="text-sm text-muted-foreground">
                  Restaurer la version <strong>{restoreVersion}</strong> ?
                </p>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setRestoreVersion(null)}
                    disabled={restoreMutation.isPending}
                    className="touch-manipulation min-h-[44px] sm:min-h-0"
                  >
                    Annuler
                  </Button>
                  <Button
                    variant="default"
                    size="sm"
                    onClick={handleRestore}
                    disabled={restoreMutation.isPending}
                    className="touch-manipulation min-h-[44px] sm:min-h-0"
                  >
                    {restoreMutation.isPending ? (
                      <>
                        <Loader2 className="w-4 h-4 sm:mr-2 animate-spin" aria-hidden="true" />
                        <span className="hidden sm:inline">Restauration...</span>
                      </>
                    ) : (
                      <>
                        <RotateCcw className="w-4 h-4 sm:mr-2" aria-hidden="true" />
                        <span className="hidden sm:inline">Confirmer</span>
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </Dialog>
    </>
  );
}

