import React, { useState, useEffect } from 'react';
import { Download, Loader2, FileText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { api } from '@/lib/api/client';
import { toast } from 'sonner';
import SEOHead from '@/components/SEOHead';

interface DownloadItem {
  download_id: string;
  download_url: string;
  product_id: number;
  product_name: string;
  product_url: string;
  download_name: string;
  order_id: number;
  order_key: string;
  downloads_remaining: string;
  access_expires: string | null;
  file: {
    name: string;
    file: string;
  };
}

export default function Downloads() {
  const [downloads, setDownloads] = useState<DownloadItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDownloads = async () => {
      try {
        setIsLoading(true);
        const data = await api.get<DownloadItem[]>('/account/downloads');
        setDownloads(data);
      } catch (err: any) {
        console.error('Failed to fetch downloads:', err);
        setError(err.message || 'Failed to load downloads');
      } finally {
        setIsLoading(false);
      }
    };

    fetchDownloads();
  }, []);

  const handleDownload = (downloadUrl: string, fileName: string) => {
    // Open download in new tab
    window.open(downloadUrl, '_blank');
    toast.success(`Downloading ${fileName}`);
  };

  if (isLoading) {
    return (
      <div>
        <h1 className="text-2xl font-bold mb-6">Downloads</h1>
        <div className="text-center py-12">
          <Loader2 className="w-12 h-12 text-gray-400 mx-auto mb-4 animate-spin" />
          <p className="text-gray-600">Loading your downloads...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div>
        <h1 className="text-2xl font-bold mb-6">Downloads</h1>
        <div className="text-center py-12">
          <p className="text-red-600">{error}</p>
          <Button
            onClick={() => window.location.reload()}
            variant="outline"
            className="mt-4"
          >
            Try Again
          </Button>
        </div>
      </div>
    );
  }

  if (downloads.length === 0) {
    return (
      <div>
        <h1 className="text-2xl font-bold mb-6">Downloads</h1>
        <div className="text-center py-12">
          <Download className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <p className="text-gray-600 mb-2">No downloads available</p>
          <p className="text-sm text-gray-500">
            Downloads will appear here after you purchase downloadable products.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <SEOHead title="Downloads" description="Your purchased downloads" />
      <h1 className="text-2xl font-bold mb-6">Downloads</h1>

      <div className="space-y-4">
        {downloads.map((download) => (
          <div
            key={`${download.download_id}-${download.order_id}`}
            className="bg-white border rounded-lg p-4 hover:shadow-md transition-shadow"
          >
            <div className="flex items-start justify-between gap-4">
              <div className="flex items-start gap-3 min-w-0 flex-1">
                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                  <FileText className="w-5 h-5 text-blue-600" />
                </div>
                <div className="min-w-0 flex-1">
                  <h3 className="font-semibold text-gray-900 truncate">
                    {download.product_name}
                  </h3>
                  <p className="text-sm text-gray-600 truncate">
                    {download.download_name || download.file?.name || 'Download'}
                  </p>
                  <div className="flex flex-wrap gap-2 mt-2 text-xs text-gray-500">
                    <span className="bg-gray-100 px-2 py-1 rounded">
                      Order #{download.order_id}
                    </span>
                    {download.downloads_remaining && download.downloads_remaining !== 'unlimited' && (
                      <span className="bg-yellow-100 text-yellow-700 px-2 py-1 rounded">
                        {download.downloads_remaining} downloads left
                      </span>
                    )}
                    {download.access_expires && (
                      <span className="bg-orange-100 text-orange-700 px-2 py-1 rounded">
                        Expires: {new Date(download.access_expires).toLocaleDateString()}
                      </span>
                    )}
                  </div>
                </div>
              </div>

              <Button
                size="sm"
                onClick={() => handleDownload(download.download_url, download.download_name || 'file')}
                className="flex-shrink-0"
              >
                <Download className="w-4 h-4 mr-2" />
                Download
              </Button>
            </div>
          </div>
        ))}
      </div>

      {downloads.length > 0 && (
        <p className="text-sm text-gray-500 mt-6 text-center">
          {downloads.length} {downloads.length === 1 ? 'download' : 'downloads'} available
        </p>
      )}
    </div>
  );
}
