import { useState, useEffect } from 'react';
import { Dialog } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreateShareLink } from '../hooks/usePlaylist';
import { useToast } from '@/hooks/useToast';
import { Copy, Check, Loader2 } from 'lucide-react';
import { parseApiError } from '@/utils/apiErrorHandler';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';

// FE-PAGE-008: Complete Playlist Detail page implementation - Share Modal

interface SharePlaylistModalProps {
  open: boolean;
  onClose: () => void;
  playlistId: string;
  playlistTitle?: string;
}

export function SharePlaylistModal({
  open,
  onClose,
  playlistId,
}: SharePlaylistModalProps) {
  const [shareLink, setShareLink] = useState<string | null>(null);
  const [isCopied, setIsCopied] = useState(false);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const createShareLinkMutation = useCreateShareLink();
  const toast = useToast();

  useEffect(() => {
    if (open && !shareLink && !createShareLinkMutation.isPending) {
      handleCreateShare();
    }
  }, [open]);

  const handleCreateShare = async () => {
    try {
      setMutationError(null);
      const share = await createShareLinkMutation.mutateAsync(playlistId);
      // PlaylistShareLink has share_token property
      const url = `${window.location.origin}/playlists/shared/${share.share_token}`;
      setShareLink(url);
      setRetryCount(0);
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      setMutationError(new Error(apiError.message));
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    try {
      await handleCreateShare();
    } catch (error) {
      // Error will be handled by handleCreateShare
    }
  };

  const handleCopy = async () => {
    if (!shareLink) return;
    try {
      await navigator.clipboard.writeText(shareLink);
      setIsCopied(true);
      toast.success('Link copied to clipboard');
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err: unknown) {
      toast.error('Failed to copy link');
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Share Playlist"
      variant="default"
      size="md"
    >
      <div className="space-y-4">
        {mutationError && (
          <ErrorDisplay
            error={mutationError}
            variant="banner"
            severity="error"
            context={{
              action: 'creating share link',
              resource: 'playlist',
              resourceId: playlistId,
            }}
            onRetry={retryCount < 3 ? handleRetry : undefined}
            onDismiss={() => {
              setMutationError(null);
              setRetryCount(0);
            }}
          />
        )}
        {createShareLinkMutation.isPending ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-6 w-6 animate-spin mr-2" />
            <span>Creating share link...</span>
          </div>
        ) : shareLink ? (
          <>
            <div className="space-y-2">
              <Label>Share Link</Label>
              <div className="flex gap-2">
                <Input value={shareLink} readOnly className="flex-1" />
                <Button onClick={handleCopy} variant="outline">
                  {isCopied ? (
                    <Check className="h-4 w-4" />
                  ) : (
                    <Copy className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            <div className="text-xs text-muted-foreground">
              Anyone with this link can view the playlist
            </div>
            <div className="flex justify-end gap-2 pt-4">
              <Button variant="outline" onClick={onClose}>
                Close
              </Button>
              <Button onClick={handleCopy}>
                <Copy className="mr-2 h-4 w-4" />
                Copy Link
              </Button>
            </div>
          </>
        ) : (
          <div className="text-center text-destructive py-4">
            Failed to create share link
          </div>
        )}
      </div>
    </Dialog>
  );
}
