'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Search,
  Download,
  Share2,
  Trash2,
  File,
  Clock,
  Users,
  MoreVertical,
  Copy,
  RefreshCw,
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { formatFileSize, formatTimeRemaining } from '@/lib/utils';

interface Transfer {
  id: number; // probably `Int` in Prisma
  senderEmail: string;
  recipientEmail: string;
  message?: string;
  files: Array<{
    id: number;
    name: string;
    size: number;
  }>;
  createdAt: string;
  expiresAt: string;
  downloadCount: number;
  downloadUrl: string;
  status: 'ACTIVE' | 'EXPIRED' | 'DELETED';
  totalFiles: number;
  totalSize: number;
}

export function MyTransfers() {
  const { data: session } = useSession();
  const [transfers, setTransfers] = useState<Transfer[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const filteredTransfers = transfers.filter(
    (transfer) =>
      transfer.recipientEmail
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      transfer.files.some((file) =>
        file.name.toLowerCase().includes(searchTerm.toLowerCase())
      )
  );

  const fetchTransfers = useCallback(async () => {
    if (!session?.user?.email) return;

    setIsLoading(true);
    try {
      const response = await fetch('/api/transfers');
      if (response.ok) {
        const data = await response.json();
        setTransfers(data.transfers);
        console.log('Transfers:', data.transfers);
      } else {
        toast.error('Failed to fetch transfers');
      }
    } catch (error) {
      console.error(error);
      toast.error('Failed to fetch transfers');
    } finally {
      setIsLoading(false);
    }
  }, [session?.user?.email]);

  useEffect(() => {
    fetchTransfers();
  }, [fetchTransfers]);

  const handleResend = async (transferId: number) => {
    try {
      const response = await fetch(`/api/transfers/${transferId}/resend`, {
        method: 'POST',
      });

      if (response.ok) {
        toast.success('Transfer resend successful!');
      } else {
        toast.error('Failed to resend transfer');
      }
    } catch (error) {
      console.error(error);
      toast.error('Failed to resend transfer');
    }
  };

  const handleDelete = async (transferId: number) => {
    try {
      const response = await fetch(`/api/transfers/${transferId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        setTransfers((prev) => prev.filter((t) => t.id !== transferId));
        toast.success('Transfer deleted successfully');
      } else {
        toast.error('Failed to delete transfer');
      }
    } catch (error) {
      console.error(error);
      toast.error('Failed to delete transfer');
    }
  };

const copyShareLink = (transferId: number) => {
  const transfer = transfers.find((t) => t.id === transferId);

  if (!transfer?.downloadUrl) {
    toast.error('Download URL not found.');
    return;
  }

  const shareUrl = `${window.location.origin}/download/${transfer.downloadUrl}`;
  navigator.clipboard.writeText(shareUrl);
  toast.success('Share link copied to clipboard!');
};


  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ACTIVE':
        return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
      case 'EXPIRED':
        return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
      case 'DELETED':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400';
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row gap-4 justify-between">
        <div className="flex gap-2 flex-1">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
            <Input
              placeholder="Search transfers..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <Button
            onClick={fetchTransfers}
            disabled={isLoading}
            variant="outline"
          >
            {isLoading ? (
              <RefreshCw className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
          </Button>
        </div>
      </div>

      {transfers.length === 0 && !isLoading && (
        <div className="text-center py-12">
          <div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4">
            <File className="w-8 h-8 text-slate-400" />
          </div>
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">
            No transfers found
          </h3>
          <p className="text-slate-500 dark:text-slate-400">
            You haven&apos;t sent any transfers yet
          </p>
        </div>
      )}

      {filteredTransfers.length > 0 && (
        <div className="grid grid-cols-1 gap-4">
          {filteredTransfers.map((transfer) => (
            <Card
              key={transfer.id}
              className="bg-white/60 dark:bg-slate-800/60 backdrop-blur-sm border-white/20 dark:border-slate-700/20 hover:bg-white/80 dark:hover:bg-slate-800/80 transition-all"
            >
              <CardContent className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center">
                        <File className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <h4 className="font-semibold text-slate-900 dark:text-slate-100">
                          To: {transfer.recipientEmail}
                        </h4>
                        <p className="text-sm text-slate-500 dark:text-slate-400">
                          {transfer.totalFiles} file
                          {transfer.totalFiles !== 1 ? 's' : ''} •{' '}
                          {formatFileSize(transfer.totalSize)}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 text-xs text-slate-500 dark:text-slate-400 mb-3">
                      <div className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {format(new Date(transfer.createdAt), 'MMM dd, yyyy')}
                      </div>
                      <div className="flex items-center gap-1">
                        <Download className="w-3 h-3" />
                        {transfer.downloadCount} downloads
                      </div>
                      <div className="flex items-center gap-1">
                        <Users className="w-3 h-3" />
                        {formatTimeRemaining(new Date(transfer.expiresAt))}
                      </div>
                    </div>

                    <Badge className={getStatusColor(transfer.status)}>
                      {transfer.status.toLowerCase()}
                    </Badge>
                  </div>
                  {transfer.status === 'ACTIVE' && (
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8 w-8 p-0"
                        >
                          <MoreVertical className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem
                          onClick={() => copyShareLink(transfer.id)}
                        >
                          <Copy className="w-4 h-4 mr-2" />
                          Copy Link
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => handleResend(transfer.id)}
                        >
                          <Share2 className="w-4 h-4 mr-2" />
                          Resend
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => handleDelete(transfer.id)}
                          className="text-red-600 dark:text-red-400"
                        >
                          <Trash2 className="w-4 h-4 mr-2" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  )}
                </div>

                {transfer.message && (
                  <div className="bg-slate-50 dark:bg-slate-800/50 rounded-lg p-3 mb-4">
                    <p className="text-sm text-slate-600 dark:text-slate-400">
                      &ldquo;{transfer.message}&rdquo;
                    </p>
                  </div>
                )}

                <div className="space-y-2">
                  <p className="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">
                    Files
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {transfer.files.slice(0, 3).map((file) => (
                      <div
                        key={file.id}
                        className="bg-slate-100 dark:bg-slate-700 rounded-md px-2 py-1 text-xs text-slate-600 dark:text-slate-400"
                      >
                        {file.name}
                      </div>
                    ))}
                    {transfer.files.length > 3 && (
                      <div className="bg-slate-100 dark:bg-slate-700 rounded-md px-2 py-1 text-xs text-slate-600 dark:text-slate-400">
                        +{transfer.files.length - 3} more
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {filteredTransfers.length === 0 && searchTerm && transfers.length > 0 && (
        <div className="text-center py-8">
          <p className="text-slate-500 dark:text-slate-400">
            No transfers found matching &ldquo;{searchTerm}&rdquo;
          </p>
        </div>
      )}
    </div>
  );
}
