'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Download,
  File,
  Clock,
  Shield,
  User,
  MessageSquare,
  Lock,
  Eye,
  EyeOff,
  AlertCircle,
  HardDrive,
} from 'lucide-react';
import { toast } from 'sonner';
import { formatFileSize, formatTimeRemaining } from '@/lib/utils';
import { saveResponseToDisk, DownloadCancelled } from '@/lib/download';

interface TransferFile {
  id: number;
  name: string;
  size: number;
}

interface TransferInfo {
  senderEmail: string;
  expiresAt: string;
  // Pre-authentication shape
  fileCount?: number;
  totalSize: number;
  requiresPassword?: boolean;
  // Post-verification shape
  message?: string | null;
  totalFiles?: number;
  files?: TransferFile[];
}

export default function DownloadPage() {
  const { id } = useParams() as { id: string };

  const [transfer, setTransfer] = useState<TransferInfo | null>(null);
  const [password, setPassword] = useState('');
  const [status, setStatus] = useState('');

  const [showPassword, setShowPassword] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [passwordError, setPasswordError] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);
  const [downloadingFiles, setDownloadingFiles] = useState<Set<number>>(
    new Set()
  );
  const [downloadingAll, setDownloadingAll] = useState(false);
  const [downloadedFiles, setDownloadedFiles] = useState<Set<number>>(
    new Set()
  );

  useEffect(() => {
    if (!id) return;

    const loadTransfer = async () => {
      try {
        const res = await fetch(`/api/download?id=${encodeURIComponent(id)}`);

        const data = await res.json();

        if (data.success) {
          setTransfer(data.transfer);
        } else {
          setStatus(data.message || 'Download not found or expired.');
        }
      } catch (err) {
        console.error(err);
        setStatus('Failed to load transfer.');
      }
    };

    loadTransfer();
  }, [id]);

  const downloadFile = async (file: TransferFile) => {
    setDownloadingFiles((prev) => new Set(prev).add(file.id));
    setStatus(`Downloading ${file.name}...`);

    try {
      // POST so the password stays out of the URL (and therefore out of access
      // logs and Referer headers).
      const res = await fetch(`/api/file/${encodeURIComponent(id)}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password, fileId: file.id }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => null);
        throw new Error(err?.error || 'File not found or invalid password.');
      }

      // Streams straight to disk where supported, so a multi-GB file is never
      // held in browser memory.
      await saveResponseToDisk(res, file.name.replace(/\.enc$/, '') || 'file');

      setDownloadedFiles((prev) => new Set(prev).add(file.id));
      setStatus('');
      toast.success(`${file.name} downloaded`);
    } catch (err: unknown) {
      if (err instanceof DownloadCancelled) {
        setStatus('');
        return;
      }
      console.error(err);
      const detail = err instanceof Error ? err.message : String(err);
      setStatus(`Download failed: ${detail}`);
      toast.error(detail);
    } finally {
      setDownloadingFiles((prev) => {
        const next = new Set(prev);
        next.delete(file.id);
        return next;
      });
    }
  };

  const handleDecrypt = async () => {
    if (!transfer?.files?.length) return;
    setDownloadingAll(true);
    try {
      // Sequential: parallel downloads of multi-GB files would compete for
      // bandwidth and memory, and each needs its own save prompt anyway.
      for (const file of transfer.files) {
        await downloadFile(file);
      }
    } finally {
      setDownloadingAll(false);
    }
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsVerifying(true);
    setPasswordError('');
    setStatus('');

    try {
      const res = await fetch(`/api/verify`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, password }),
      });

      const data = await res.json();

      if (data.success) {
        setTransfer(data.transfer);
        setIsAuthenticated(true);
      } else {
        setPasswordError(
          data.message || 'Incorrect password. Please try again.'
        );
      }
    } catch (err) {
      console.error(err);
      setPasswordError('Something went wrong. Try again.');
    } finally {
      setIsVerifying(false);
    }
  };

  const isFileDownloading = (fileId: number) => downloadingFiles.has(fileId);
  const isFileDownloaded = (fileId: number) => downloadedFiles.has(fileId);

  if (!transfer) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-slate-900 dark:via-slate-800 dark:to-slate-900 flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center mx-auto mb-4 animate-pulse">
            <File className="w-8 h-8 text-white" />
          </div>
          <p className="text-slate-600 dark:text-slate-400">
            Loading transfer...
          </p>
        </div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-gray-900 relative overflow-hidden">
        {/* Modern Background */}
        <div className="absolute inset-0 bg-gradient-to-br from-gray-900 via-blue-900/20 to-purple-900/20"></div>
        <div className="absolute inset-0 bg-[url('https://images.pexels.com/photos/1103970/pexels-photo-1103970.jpeg?auto=compress&cs=tinysrgb&w=1920&h=1080&fit=crop')] bg-cover bg-center opacity-10"></div>
        <div className="absolute inset-0 bg-gradient-to-t from-gray-900/90 via-gray-900/50 to-gray-900/90"></div>

        {/* Animated Background Elements */}
        <div className="absolute top-20 left-20 w-72 h-72 bg-blue-500/10 rounded-full blur-3xl animate-pulse"></div>
        <div className="absolute bottom-20 right-20 w-96 h-96 bg-purple-500/10 rounded-full blur-3xl animate-pulse delay-1000"></div>
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-emerald-500/10 rounded-full blur-3xl animate-pulse delay-500"></div>
        <div className="relative z-10 container mx-auto px-4 py-8 max-w-lg min-h-screen flex items-center justify-center">
          <div className="w-full space-y-6">
            {/* Transfer Info Card */}
            <Card className="border-gray-800 bg-gray-900/80 backdrop-blur-xl shadow-2xl">
              <CardHeader className="text-center pb-4">
                <div className="inline-flex items-center justify-center w-16 h-16 bg-blue-600 rounded-2xl mx-auto mb-4">
                  <Download className="h-8 w-8 text-white" />
                </div>
                <CardTitle className="text-xl font-bold text-white mb-2">
                  File Transfer
                </CardTitle>
                <CardDescription className="text-gray-400">
                  You have received files from {transfer.senderEmail}
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-0">
                {/* Sender Info */}
                <div className="space-y-3 mb-6">
                  <div className="flex items-center gap-3 text-sm">
                    <User className="h-4 w-4 text-gray-500 flex-shrink-0" />
                    <div>
                      <div className="text-gray-400">
                        {transfer.senderEmail}
                      </div>
                    </div>
                  </div>
                </div>

                <Separator className="bg-gray-800 mb-6" />

                {/* Transfer Stats */}
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="flex items-center gap-2">
                    <File className="h-4 w-4 text-gray-500" />
                    <div>
                      <div className="text-gray-400">Files</div>
                      <div className="text-white font-medium">
                        {transfer.fileCount}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <HardDrive className="h-4 w-4 text-gray-500" />
                    <div>
                      <div className="text-gray-400">Total Size</div>
                      <div className="text-white font-medium">
                        {formatFileSize(transfer.totalSize)}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="mt-4 flex items-center gap-2 text-sm">
                  <Clock className="h-4 w-4 text-gray-500" />
                  <div>
                    <span className="text-gray-400">Expires: </span>
                    <span className="text-white font-medium">
                      {formatTimeRemaining(new Date(transfer.expiresAt))}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card className="border-gray-800 bg-gray-900/80 backdrop-blur-xl shadow-2xl">
              <CardHeader className="text-center pb-6">
                <div className="inline-flex items-center justify-center w-12 h-12 bg-orange-600 rounded-xl mx-auto mb-3">
                  <Lock className="h-6 w-6 text-white" />
                </div>
                <CardTitle className="text-lg font-bold text-white mb-1">
                  Protected Transfer
                </CardTitle>
                <CardDescription className="text-gray-400">
                  Enter the password to access your files
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-0">
                <form onSubmit={handlePasswordSubmit} className="space-y-6">
                  <div className="space-y-2">
                    <Label
                      htmlFor="password"
                      className="text-sm font-medium text-gray-300"
                    >
                      Password
                    </Label>
                    <div className="relative">
                      <Input
                        id="password"
                        type={showPassword ? 'text' : 'password'}
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder="Enter transfer password"
                        className="bg-gray-800 border-gray-700 text-white placeholder-gray-500 pr-12 h-12 focus:border-blue-500 focus:ring-blue-500"
                        required
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-300 transition-colors"
                      >
                        {showPassword ? (
                          <EyeOff className="h-5 w-5" />
                        ) : (
                          <Eye className="h-5 w-5" />
                        )}
                      </button>
                    </div>
                    {passwordError && (
                      <div className="flex items-center gap-2 text-red-400 text-sm mt-2">
                        <AlertCircle className="h-4 w-4" />
                        {passwordError}
                      </div>
                    )}
                  </div>

                  <Button
                    type="submit"
                    disabled={isVerifying || !password}
                    className="w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-medium shadow-lg hover:shadow-xl transition-all duration-200"
                  >
                    {isVerifying ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2" />
                        Verifying...
                      </>
                    ) : (
                      <>
                        <Shield className="h-5 w-5 mr-2" />
                        Access Files
                      </>
                    )}
                  </Button>
                </form>

                <div className="mt-6 pt-6 border-t border-gray-800">
                  <div className="flex items-center justify-center gap-2 text-sm text-gray-500">
                    <Shield className="h-4 w-4" />
                    <span>Secure encrypted transfer</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-900 relative overflow-hidden">
      {/* Modern Background */}
      <div className="absolute inset-0 bg-gradient-to-br from-gray-900 via-blue-900/20 to-purple-900/20"></div>
      <div className="absolute inset-0 bg-[url('https://images.pexels.com/photos/1103970/pexels-photo-1103970.jpeg?auto=compress&cs=tinysrgb&w=1920&h=1080&fit=crop')] bg-cover bg-center opacity-10"></div>
      <div className="absolute inset-0 bg-gradient-to-t from-gray-900/90 via-gray-900/50 to-gray-900/90"></div>

      {/* Animated Background Elements */}
      <div className="absolute top-20 left-20 w-72 h-72 bg-blue-500/10 rounded-full blur-3xl animate-pulse"></div>
      <div className="absolute bottom-20 right-20 w-96 h-96 bg-purple-500/10 rounded-full blur-3xl animate-pulse delay-1000"></div>

      <div className="relative z-10 container mx-auto px-4 py-8 max-w-4xl">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center gap-2 mb-4">
            <div className="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
              <Download className="h-6 w-6 text-white" />
            </div>
            <span className="text-2xl font-bold text-white">FileTransfer</span>
          </div>
          <h1 className="text-3xl font-bold text-white mb-2">
            Download Your Files
          </h1>
          <p className="text-gray-400 text-lg">
            Your files are ready for download
          </p>
        </div>

        {/* Transfer Info Card */}
        <Card className="mb-8 border-gray-800 bg-gray-900/80 backdrop-blur-xl shadow-2xl">
          <CardHeader className="pb-4">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <CardTitle className="text-xl mb-2 text-white">
                  Transfer from {transfer.senderEmail}
                </CardTitle>
                <CardDescription className="text-base">
                  <div className="flex items-center gap-2 mb-1 text-gray-400">
                    <User className="h-4 w-4" />
                    {transfer.senderEmail}
                  </div>
                </CardDescription>
              </div>
              <Badge
                variant="secondary"
                className="bg-emerald-900/50 text-emerald-300 border-emerald-700"
              >
                <Shield className="h-3 w-3 mr-1" />
                Secure Transfer
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="pt-0">
            {transfer.message && (
              <div className="mb-6">
                <div className="flex items-start gap-2 mb-2">
                  <MessageSquare className="h-4 w-4 text-gray-500 mt-1 flex-shrink-0" />
                  <span className="text-sm font-medium text-gray-300">
                    Message:
                  </span>
                </div>
                <p className="text-gray-400 leading-relaxed ml-6">
                  {transfer.message}
                </p>
              </div>
            )}

            <div className="flex flex-wrap items-center gap-6 text-sm text-gray-400">
              <div className="flex items-center gap-2">
                <File className="h-4 w-4" />
                <span>
                  {transfer.files?.length ?? 0}{' '}
                  {transfer.files?.length === 1 ? 'file' : 'files'}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Download className="h-4 w-4" />
                <span>{formatFileSize(transfer.totalSize)} total</span>
              </div>
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4" />
                <span>
                  Expires {formatTimeRemaining(new Date(transfer.expiresAt))}
                </span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Download All Button */}
        <div className="mb-6">
          <Button
            onClick={handleDecrypt}
            disabled={downloadingAll}
            size="lg"
            className="w-full h-12 px-8 bg-blue-600 hover:bg-blue-700 text-white shadow-lg hover:shadow-xl transition-all duration-200"
          >
            {downloadingAll ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2" />
                Preparing Download...
              </>
            ) : (
              <>
                <Download className="h-5 w-5 mr-2" />
                Download All Files {formatFileSize(transfer.totalSize)}
              </>
            )}
          </Button>
        </div>

        <Separator className="mb-6 bg-gray-800" />

        {/* Files List */}
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-white mb-4">
            Files in this transfer
          </h2>
          {transfer.files?.map((file) => (
            <Card
              key={file.id}
              className="border-gray-800 bg-gray-900/60 backdrop-blur-xl hover:bg-gray-900/80 transition-all duration-200"
            >
              <CardContent className="flex items-center justify-between gap-4 py-4">
                <div className="min-w-0">
                  <h3 className="font-medium text-white truncate">{file.name}</h3>
                  <p className="text-sm text-gray-400">
                    {formatFileSize(file.size)}
                  </p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => downloadFile(file)}
                  disabled={isFileDownloading(file.id) || downloadingAll}
                  className="shrink-0"
                >
                  {isFileDownloading(file.id) ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-2 border-current border-t-transparent mr-2" />
                      Downloading
                    </>
                  ) : isFileDownloaded(file.id) ? (
                    <>
                      <Download className="h-4 w-4 mr-2" />
                      Download again
                    </>
                  ) : (
                    <>
                      <Download className="h-4 w-4 mr-2" />
                      Download
                    </>
                  )}
                </Button>
              </CardContent>
            </Card>
          ))}
        </div>

        {status && (
          <p className="mt-4 text-sm text-gray-400 text-center">{status}</p>
        )}

        {/* Footer */}
        <div className="mt-12 text-center">
          <div className="inline-flex items-center gap-2 text-sm text-gray-500 mb-4">
            <Shield className="h-4 w-4" />
            <span>All downloads are secure and encrypted</span>
          </div>
          <p className="text-xs text-gray-600">
            This transfer will expire on {transfer.expiresAt}. Download your
            files before this date.
          </p>
        </div>
      </div>
    </div>
  );
}
