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 { createTrackShare, Share } from '../api/trackApi';
import { useToast } from '@/hooks/useToast';
import { Copy, Check } from 'lucide-react';

// 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,
  trackTitle,
}: ShareDialogProps) {
  const [share, setShare] = useState<Share | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [isCopied, setIsCopied] = useState(false);
  const [expiresIn] = useState<number>(7); // days
  const [isPublic] = useState(true);
  const toast = useToast();

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

  const handleCreateShare = async () => {
    try {
      setIsCreating(true);
      const newShare = await createTrackShare(trackId, {
        expires_in_days: expiresIn,
        is_public: isPublic,
      });
      setShare(newShare);
    } catch (error: any) {
      toast.error(error.message || 'Failed to create share link');
    } 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) {
      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">
        {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 {expiresIn} 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>
  );
}

