import { useState, useEffect, useRef } 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 { tracksApi, type Share } from '@/services/api/tracks';
import { useToast } from '@/hooks/useToast';
import { Copy, Check } from 'lucide-react';
import { parseApiError } from '@/utils/apiErrorHandler';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';

// FE-PAGE-007: Complete Track Detail page implementation - Share Dialog

interface ShareDialogProps {
  open: boolean;
  onClose: () => void;
  trackId: string;
  trackTitle: string;
}

export function ShareDialog({ open, onClose, trackId }: ShareDialogProps) {
  const [share, setShare] = useState<Share | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [isCopied, setIsCopied] = useState(false);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);
  const toast = useToast();

  useEffect(() => {
    if (open && !share) {
      handleCreateShare();
    }
  }, [open]);

  const handleCreateShare = async () => {
    // Action 3.4.1.3: Store mutation for retry
    const performMutation = async () => {
      const expiresAt = new Date();
      expiresAt.setDate(expiresAt.getDate() + 7); // 7 days from now
      const newShare = await tracksApi.createShare(trackId, {
        permissions: 'read',
        expires_at: expiresAt.toISOString(),
      });
      setShare(newShare);
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setIsCreating(true);
    setMutationError(null);

    try {
      await performMutation();
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      setMutationError(new Error(apiError.message));
    } finally {
      setIsCreating(false);
    }
  };

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

    setRetryCount((prev) => prev + 1);
    setIsCreating(true);
    try {
      await lastMutationRef.current();
    } catch (error) {
      // Error will be handled by the mutation function
    } finally {
      setIsCreating(false);
    }
  };

  const handleCopy = async () => {
    if (!share) return;
    const shareUrl = `${window.location.origin}/tracks/shared/${share.token}`;
    try {
      await navigator.clipboard.writeText(shareUrl);
      setIsCopied(true);
      toast.success('Link copied to clipboard');
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err: unknown) {
      toast.error('Failed to copy link');
    }
  };

  const shareUrl = share
    ? `${window.location.origin}/tracks/shared/${share.token}`
    : '';

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Share Track"
      variant="default"
      size="md"
    >
      <div className="space-y-4">
        {mutationError && (
          <ErrorDisplay
            error={mutationError}
            variant="banner"
            severity="error"
            context={{
              action: 'creating share link',
              resource: 'track',
              resourceId: trackId,
            }}
            onRetry={retryCount < 3 ? handleRetry : undefined}
            onDismiss={() => {
              setMutationError(null);
              setRetryCount(0);
              lastMutationRef.current = null;
            }}
          />
        )}
        {isCreating ? (
          <div className="text-center py-4">Creating share link...</div>
        ) : share ? (
          <>
            <div className="space-y-2">
              <Label>Share Link</Label>
              <div className="flex gap-2">
                <Input value={shareUrl} 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">
              This link will expire in 7 day(s)
            </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">
            Failed to create share link
          </div>
        )}
      </div>
    </Dialog>
  );
}
