"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, MessageSquare, Mail, MailOpen, Loader2 } from "lucide-react";
import Link from 'next/link';
import { useSession } from "next-auth/react";

interface Email {
  id: string;
  subject: string;
  from: string;
  fromName?: string;
  date: string;
  read: boolean;
  starred: boolean;
  folder: string;
}

interface EmailProps {
  limit?: number;
  showTitle?: boolean;
  showRefresh?: boolean;
  showMoreLink?: boolean;
  folder?: string;
  cardClassName?: string;
  title?: string;
}

export function Email({
  limit = 5,
  showTitle = true,
  showRefresh = true,
  showMoreLink = true,
  folder = "INBOX",
  cardClassName = "h-full",
  title = "Unread Emails"
}: EmailProps) {
  const [emails, setEmails] = useState<Email[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mailUrl, setMailUrl] = useState<string | null>(null);
  const { status } = useSession();

  useEffect(() => {
    if (status === "authenticated") {
      fetchEmails();
    }
  }, [status, folder, limit]);

  const fetchEmails = async (isRefresh = false) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/courrier?folder=${folder}&page=1&perPage=${limit}`); 
      if (!response.ok) {
        throw new Error('Failed to fetch emails');
      }

      const data = await response.json();
      
      if (data.error) {
        setError(data.error);
        setEmails([]);
      } else {
        // Transform data format if needed
        const transformedEmails = data.emails.map((email: any) => ({
          id: email.id,
          subject: email.subject || '(No subject)',
          from: email.from[0]?.address || '',
          fromName: email.from[0]?.name || '',
          date: email.date,
          read: email.flags.seen,
          starred: email.flags.flagged,
          folder: email.folder
        })).slice(0, limit); 
        
        setEmails(transformedEmails);
        setMailUrl('/courrier');
      }
    } catch (error) {
      setError('Failed to load emails');
      setEmails([]);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return new Intl.DateTimeFormat('fr-FR', {
        month: 'short',
        day: 'numeric'
      }).format(date);
    } catch (e) {
      return '';
    }
  };

  const renderContent = () => {
    if (error) {
      return (
        <div className="text-center py-4 text-gray-500">
          {error}
        </div>
      );
    }
    
    if (loading && emails.length === 0) {
      return (
        <div className="text-center py-6 flex flex-col items-center">
          <Loader2 className="h-6 w-6 animate-spin text-gray-400 mb-2" />
          <p className="text-gray-500">Loading emails...</p>
        </div>
      );
    }
    
    if (emails.length === 0) {
      return (
        <div className="text-center py-6">
          <p className="text-gray-500">No emails found</p>
        </div>
      );
    }
    
    return (
      <div className="space-y-3">
        {emails.map((email) => (
          <div key={email.id} className="flex items-start gap-3 py-1 border-b border-gray-100 last:border-0">
            <div className="pt-1">
              {email.read ? 
                <MailOpen className="h-4 w-4 text-gray-400" /> : 
                <Mail className="h-4 w-4 text-blue-500" />
              }
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex justify-between">
                <p className="font-medium truncate" style={{maxWidth: '180px'}}>{email.fromName || email.from.split('@')[0]}</p>
                <p className="text-xs text-gray-500">{formatDate(email.date)}</p>
              </div>
              <p className="text-sm text-gray-700 truncate">{email.subject}</p>
            </div>
          </div>
        ))}
        
        {showMoreLink && mailUrl && (
          <div className="pt-2">
            <Link href={mailUrl} className="text-sm text-blue-600 hover:text-blue-800">
              View all emails →
            </Link>
          </div>
        )}
      </div>
    );
  };

  return (
    <Card className={cardClassName}>
      {showTitle && (
        <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
          <CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-gray-600" />
            {title}
          </CardTitle>
          {showRefresh && (
            <Button 
              variant="ghost" 
              size="icon" 
              onClick={() => fetchEmails(true)}
              disabled={loading}
            >
              {loading ? 
                <Loader2 className="h-4 w-4 animate-spin" /> : 
                <RefreshCw className="h-4 w-4" />
              }
            </Button>
          )}
        </CardHeader>
      )}
      <CardContent className="p-4">
        {renderContent()}
      </CardContent>
    </Card>
  );
} 