/**
 * Composant PlaylistActions
 * T0460: Create Playlist Detail Page
 */

import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Dialog } from '@/components/ui/dialog';
import { Edit, Trash2, Loader2, Share2, CheckCircle2 } from 'lucide-react';
import { useUpdatePlaylist, useDeletePlaylist } from '../hooks/usePlaylist';
import { useToast } from '@/hooks/useToast';
import { usePlaylistPermissions } from '@/features/playlists/hooks/usePlaylistPermissions';
import type { Playlist, UpdatePlaylistRequest } from '../types';
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog';

interface PlaylistActionsProps {
  playlist: Playlist;
  onUpdated?: () => void;
  onShareClick?: () => void;
  canShare?: boolean;
  className?: string;
}

export function PlaylistActions({
  playlist,
  onUpdated,
  onShareClick,
  canShare = false,
  className,
}: PlaylistActionsProps) {
  const navigate = useNavigate();
  const { success: showSuccessToast, error: showError } = useToast();
  // Alias showSuccessToast to avoid conflict with state variable showSuccess
  const showSuccessMessage = showSuccessToast;
  const permissions = usePlaylistPermissions(playlist);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editForm, setEditForm] = useState<UpdatePlaylistRequest>({
    title: playlist.title,
    description: playlist.description,
    is_public: playlist.is_public,
    cover_url: playlist.cover_url,
  });

  const updateMutation = useUpdatePlaylist();
  const deleteMutation = useDeletePlaylist();
  const [showSuccess, setShowSuccess] = useState(false);

  // Reset success state after mutation completes
  useEffect(() => {
    if (updateMutation.isSuccess && !updateMutation.isPending) {
      setShowSuccess(true);
      const timer = setTimeout(() => {
        setShowSuccess(false);
        updateMutation.reset();
      }, 2000);
      return () => clearTimeout(timer);
    }
    return undefined;
  }, [updateMutation.isSuccess, updateMutation.isPending, updateMutation]);

  // Ne pas afficher les actions si l'utilisateur n'a aucune permission
  if (!permissions.canEdit && !permissions.canDelete && !canShare) {
    return null;
  }

  const handleUpdate = async () => {
    try {
      await updateMutation.mutateAsync({
        id: playlist.id,
        data: editForm,
      });
      showSuccessMessage('Playlist mise à jour avec succès');
      setShowEditDialog(false);
      onUpdated?.();
    } catch (error) {
      showError(
        error instanceof Error
          ? error.message
          : 'Erreur lors de la mise à jour',
      );
    }
  };

  const handleDeleteClick = () => {
    setShowDeleteDialog(true);
  };

  const handleDeleteConfirm = async () => {
    try {
      await deleteMutation.mutateAsync(playlist.id);
      showSuccessMessage('Playlist supprimée avec succès');
      setShowDeleteDialog(false);
      navigate('/playlists');
    } catch (error) {
      showError(
        error instanceof Error
          ? error.message
          : 'Erreur lors de la suppression',
      );
    }
  };

  return (
    <div className={className} role="group" aria-label="Actions de la playlist">
      <div className="flex flex-col sm:flex-row gap-2 sm:gap-2 mb-4 sm:mb-6">
        {permissions.canEdit && (
          <Button
            variant="outline"
            onClick={() => setShowEditDialog(true)}
            disabled={updateMutation.isPending || deleteMutation.isPending}
            aria-label="Modifier la playlist"
            className="touch-manipulation min-h-[44px] sm:min-h-0 w-full sm:w-auto"
          >
            {updateMutation.isPending ? (
              <>
                <Loader2
                  className="w-4 h-4 sm:mr-2 animate-spin"
                  aria-hidden="true"
                />
                <span className="hidden sm:inline">Enregistrement...</span>
              </>
            ) : showSuccess ? (
              <>
                <CheckCircle2
                  className="w-4 h-4 sm:mr-2 text-green-600"
                  aria-hidden="true"
                />
                <span className="hidden sm:inline">Enregistré</span>
              </>
            ) : (
              <>
                <Edit className="w-4 h-4 sm:mr-2" aria-hidden="true" />
                Modifier
              </>
            )}
          </Button>
        )}
        {canShare && onShareClick && (
          <Button
            variant="outline"
            onClick={onShareClick}
            disabled={updateMutation.isPending || deleteMutation.isPending}
            aria-label="Partager la playlist"
            className="touch-manipulation min-h-[44px] sm:min-h-0 w-full sm:w-auto"
          >
            <Share2 className="w-4 h-4 sm:mr-2" aria-hidden="true" />
            Partager
          </Button>
        )}
        {permissions.canDelete && (
          <Button
            variant="destructive"
            onClick={handleDeleteClick}
            disabled={updateMutation.isPending || deleteMutation.isPending}
            aria-label="Supprimer la playlist"
            className="touch-manipulation min-h-[44px] sm:min-h-0 w-full sm:w-auto"
          >
            <Trash2 className="w-4 h-4 sm:mr-2" aria-hidden="true" />
            Supprimer
          </Button>
        )}
      </div>

      {/* Edit Dialog */}
      <Dialog
        open={showEditDialog}
        onClose={() => setShowEditDialog(false)}
        title="Modifier la playlist"
        variant="default"
        onConfirm={handleUpdate}
        onCancel={() => setShowEditDialog(false)}
        confirmLabel={
          updateMutation.isPending ? 'Enregistrement...' : 'Enregistrer'
        }
        cancelLabel="Annuler"
        showCancel={true}
        size="md"
        aria-label="Dialogue de modification de playlist"
      >
        <div className="space-y-4">
          <div>
            <label
              htmlFor="edit-title"
              className="block text-sm font-medium mb-2"
            >
              Titre
            </label>
            <input
              type="text"
              id="edit-title"
              value={editForm.title || ''}
              onChange={(e) =>
                setEditForm({ ...editForm, title: e.target.value })
              }
              className="w-full px-3 py-2 border rounded-md"
              placeholder="Titre de la playlist"
              aria-required="true"
            />
          </div>
          <div>
            <label
              htmlFor="edit-description"
              className="block text-sm font-medium mb-2"
            >
              Description
            </label>
            <textarea
              id="edit-description"
              value={editForm.description || ''}
              onChange={(e) =>
                setEditForm({ ...editForm, description: e.target.value })
              }
              className="w-full px-3 py-2 border rounded-md"
              rows={3}
              placeholder="Description de la playlist"
            />
          </div>
          <div>
            <label
              htmlFor="edit-cover-url"
              className="block text-sm font-medium mb-2"
            >
              URL de la couverture
            </label>
            <input
              type="url"
              id="edit-cover-url"
              value={editForm.cover_url || ''}
              onChange={(e) =>
                setEditForm({ ...editForm, cover_url: e.target.value })
              }
              className="w-full px-3 py-2 border rounded-md"
              placeholder="https://example.com/cover.jpg"
            />
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="edit-is_public"
              checked={editForm.is_public ?? false}
              onChange={(e) =>
                setEditForm({ ...editForm, is_public: e.target.checked })
              }
              className="w-4 h-4"
              aria-checked={editForm.is_public ?? false}
            />
            <label htmlFor="edit-is_public" className="text-sm font-medium">
              Playlist publique
            </label>
          </div>
          {updateMutation.isPending && (
            <div
              className="flex items-center gap-2 text-sm text-muted-foreground"
              role="status"
              aria-live="assertive"
            >
              <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
              <span>Enregistrement en cours...</span>
            </div>
          )}
        </div>
      </Dialog>

      <ConfirmationDialog
        open={showDeleteDialog}
        onClose={() => setShowDeleteDialog(false)}
        onConfirm={handleDeleteConfirm}
        title="Delete Playlist"
        description={`Are you sure you want to delete "${playlist.title}"? This action cannot be undone. All tracks in this playlist will be removed.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        variant="destructive"
        isLoading={deleteMutation.isPending}
      />
    </div>
  );
}
