'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Download, Loader2, Play, Music, Sparkles, Zap, Check } from 'lucide-react';
import { isValidYouTubeUrl } from '@/lib/utils';
import type { VideoInfo, DownloadResponse, VideoFormat, AudioFormat } from '@/lib/types';

export default function Home() {
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [videoInfo, setVideoInfo] = useState<VideoInfo | null>(null);
  const [videoFormat, setVideoFormat] = useState<VideoFormat>('mp4');
  const [audioFormat, setAudioFormat] = useState<AudioFormat>('mp3');
  const [formatType, setFormatType] = useState<'video' | 'audio'>('video');
  const [downloadResult, setDownloadResult] = useState<DownloadResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      const x = (e.clientX / window.innerWidth) * 2 - 1;
      const y = (e.clientY / window.innerHeight) * 2 - 1;
      setMousePos({ x, y });
    };

    window.addEventListener('mousemove', handleMouseMove);
    return () => window.removeEventListener('mousemove', handleMouseMove);
  }, []);

  const handleGetInfo = async () => {
    if (!url.trim()) {
      setError('Please enter a YouTube URL');
      return;
    }

    if (!isValidYouTubeUrl(url)) {
      setError('Please enter a valid YouTube URL');
      return;
    }

    setLoading(true);
    setError(null);
    setVideoInfo(null);
    setDownloadResult(null);

    try {
      const response = await fetch('/api/info', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
      });

      const data = await response.json();

      if (data.success && data.videoInfo) {
        setVideoInfo(data.videoInfo);
      } else {
        setError(data.error || 'Failed to get video information');
      }
    } catch (err: any) {
      setError(err.message || 'Failed to fetch video info');
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async () => {
    if (!url.trim()) {
      setError('Please enter a YouTube URL');
      return;
    }

    if (!isValidYouTubeUrl(url)) {
      setError('Please enter a valid YouTube URL');
      return;
    }

    setLoading(true);
    setError(null);
    setDownloadResult(null);

    try {
      const response = await fetch('/api/download', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          url,
          format: formatType === 'video' ? videoFormat : audioFormat,
          formatType,
        }),
      });

      const data: DownloadResponse = await response.json();

      if (data.success) {
        setDownloadResult(data);
        if (data.videoInfo) {
          setVideoInfo(data.videoInfo);
        }
      } else {
        setError(data.error || 'Failed to download video');
      }
    } catch (err: any) {
      setError(err.message || 'Failed to download video');
    } finally {
      setLoading(false);
    }
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className="min-h-screen relative">
      {/* Animated background */}
      <div className="animated-bg" />
      
      <div 
        className="fixed inset-0 z-[-2] pointer-events-none transition-transform duration-1000 cubic-bezier(0.1, 0.8, 0.2, 1)"
        style={{
          transform: `perspective(100vh) rotateX(${mousePos.y * -3}deg) rotateY(${mousePos.x * 3}deg) translateX(${mousePos.x * -10}px) translateY(${mousePos.y * -10}px)`
        }}
      >
        <div className="background-grid" />
      </div>

      <div className="floating-orb floating-orb-1" />
      <div className="floating-orb floating-orb-2" />
      <div className="floating-orb floating-orb-3" />

      <div className="container mx-auto px-4 py-12 md:py-20 max-w-2xl relative z-10">
        {/* Header */}
        <div className="text-center mb-10 md:mb-14 slide-up">
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-primary/10 border border-primary/20 text-primary text-sm font-medium mb-6">
            <Sparkles className="w-4 h-4" />
            Fast & Free Downloads
          </div>
          <h1 className="text-4xl md:text-6xl font-bold mb-4 gradient-text tracking-tight" data-text="Downlink">
            Downlink
          </h1>
          <p className="text-muted-foreground text-base md:text-lg max-w-md mx-auto">
            Download YouTube videos and audio in any format. No limits, no ads, just downloads.
          </p>
        </div>

        {/* URL Input Card */}
        <Card className="mb-6 glass-card slide-up slide-up-delay-1 border-0">
          <CardContent className="pt-6 pb-6">
            <div className="flex flex-col sm:flex-row gap-3">
              <div className="flex-1 relative">
                <Input
                  type="url"
                  placeholder="Paste YouTube URL here..."
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !loading) {
                      handleGetInfo();
                    }
                  }}
                  className="h-12 px-4 text-base bg-background/50 border-white/10 input-glow rounded-xl placeholder:text-muted-foreground/50"
                />
              </div>
              <Button
                onClick={handleGetInfo}
                disabled={loading}
                className="h-12 px-6 glow-button text-white border-0 rounded-xl font-medium"
              >
                {loading ? (
                  <Loader2 className="h-5 w-5 animate-spin" />
                ) : (
                  <>
                    <Zap className="h-4 w-4 mr-2" />
                    Fetch
                  </>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Error Display */}
        {error && (
          <Card className="mb-6 slide-up border-destructive/30 bg-destructive/10 backdrop-blur-xl">
            <CardContent className="py-4">
              <p className="text-destructive text-sm font-medium text-center">{error}</p>
            </CardContent>
          </Card>
        )}

        {/* Video Info Card */}
        {videoInfo && (
          <Card className="mb-6 glass-card slide-up slide-up-delay-2 border-0 overflow-hidden">
            <CardContent className="p-0">
              {videoInfo.thumbnail && (
                <div className="thumbnail-container aspect-video w-full bg-muted">
                  <img
                    src={videoInfo.thumbnail}
                    alt={videoInfo.title}
                    className="w-full h-full object-cover"
                  />
                </div>
              )}
              <div className="p-5">
                <h3 className="font-semibold text-base md:text-lg mb-2 line-clamp-2 leading-snug">
                  {videoInfo.title}
                </h3>
                <div className="flex items-center gap-3 text-sm text-muted-foreground">
                  <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-primary/10 text-primary text-xs font-medium">
                    <Play className="w-3 h-3" />
                    {formatDuration(videoInfo.duration)}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Download Options Card */}
        {videoInfo && (
          <Card className="mb-6 glass-card slide-up slide-up-delay-3 border-0">
            <CardHeader className="pb-4">
              <CardTitle className="text-lg font-semibold">Download Options</CardTitle>
              <CardDescription>
                Choose your format and quality
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-5">
              {/* Format Type Toggle */}
              <div className="grid grid-cols-2 gap-2 p-1 bg-background/30 rounded-xl">
                <button
                  onClick={() => setFormatType('video')}
                  className={`flex items-center justify-center gap-2 py-2.5 px-4 rounded-lg text-sm font-medium transition-all ${
                    formatType === 'video'
                      ? 'bg-primary text-white shadow-lg shadow-primary/25'
                      : 'text-muted-foreground hover:text-foreground hover:bg-white/5'
                  }`}
                >
                  <Play className="h-4 w-4" />
                  Video
                </button>
                <button
                  onClick={() => setFormatType('audio')}
                  className={`flex items-center justify-center gap-2 py-2.5 px-4 rounded-lg text-sm font-medium transition-all ${
                    formatType === 'audio'
                      ? 'bg-primary text-white shadow-lg shadow-primary/25'
                      : 'text-muted-foreground hover:text-foreground hover:bg-white/5'
                  }`}
                >
                  <Music className="h-4 w-4" />
                  Audio
                </button>
              </div>

              {/* Format Selection */}
              <div className="space-y-2">
                <Label className="text-sm text-muted-foreground">
                  {formatType === 'video' ? 'Video Format' : 'Audio Format'}
                </Label>
                {formatType === 'video' ? (
                  <Select
                    value={videoFormat}
                    onValueChange={(value: VideoFormat) => setVideoFormat(value)}
                  >
                    <SelectTrigger className="h-11 bg-background/50 border-white/10 rounded-xl">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="glass-card border-white/10">
                      <SelectItem value="mp4">MP4 (Recommended)</SelectItem>
                      <SelectItem value="webm">WebM</SelectItem>
                      <SelectItem value="mkv">MKV</SelectItem>
                      <SelectItem value="avi">AVI</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <Select
                    value={audioFormat}
                    onValueChange={(value: AudioFormat) => setAudioFormat(value)}
                  >
                    <SelectTrigger className="h-11 bg-background/50 border-white/10 rounded-xl">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="glass-card border-white/10">
                      <SelectItem value="mp3">MP3 (Recommended)</SelectItem>
                      <SelectItem value="m4a">M4A</SelectItem>
                      <SelectItem value="wav">WAV</SelectItem>
                      <SelectItem value="opus">Opus</SelectItem>
                    </SelectContent>
                  </Select>
                )}
              </div>

              {/* Download Button */}
              <Button
                onClick={handleDownload}
                disabled={loading}
                className="w-full h-12 glow-button text-white border-0 rounded-xl font-medium text-base"
              >
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                    Processing...
                  </>
                ) : (
                  <>
                    <Download className="mr-2 h-5 w-5" />
                    Download {formatType === 'video' ? videoFormat.toUpperCase() : audioFormat.toUpperCase()}
                  </>
                )}
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Success Card */}
        {downloadResult?.success && downloadResult.downloadUrl && (
          <Card className="slide-up success-glow backdrop-blur-xl border-0">
            <CardContent className="py-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-green-500/20 flex items-center justify-center">
                  <Check className="w-5 h-5 text-green-400" />
                </div>
                <div>
                  <h3 className="font-semibold text-green-400">Ready to Download</h3>
                  <p className="text-sm text-muted-foreground">Your file has been prepared</p>
                </div>
              </div>
              <a
                href={downloadResult.downloadUrl}
                download={downloadResult.filename}
                className="block"
              >
                <Button className="w-full h-12 bg-green-600 hover:bg-green-500 text-white border-0 rounded-xl font-medium text-base shadow-lg shadow-green-600/25 transition-all hover:shadow-green-500/30 hover:-translate-y-0.5">
                  <Download className="mr-2 h-5 w-5" />
                  Save File
                </Button>
              </a>
            </CardContent>
          </Card>
        )}

        {/* Footer */}
        <div className="text-center mt-12 text-sm text-muted-foreground/60">
          <p>Free and open source. No tracking, no ads.</p>
        </div>
      </div>
    </div>
  );
}
