"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';

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

interface EmailResponse {
  emails: Email[];
  mailUrl: string;
  error?: string;
}

export function Email() {
  const [emails, setEmails] = useState<Email[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mailUrl, setMailUrl] = useState<string | null>(null);

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

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

    try {
      const response = await fetch('/api/courrier?folder=INBOX&page=1&perPage=5' + (isRefresh ? '&refresh=true' : '')); 
      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,
          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, 5); // Only show the first 5 emails
        
        setEmails(transformedEmails);
        setMailUrl('/courrier');
      }
    } catch (error) {
      console.error('Error fetching emails:', 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 '';
    }
  };

  return (
    <Card className="h-full">
      <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" />
          Emails non lus
        </CardTitle>
        <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">
        {error ? (
          <div className="text-center py-4 text-gray-500">
            {error}
          </div>
        ) : loading && emails.length === 0 ? (
          <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">Chargement des emails...</p>
          </div>
        ) : emails.length === 0 ? (
          <div className="text-center py-6">
            <p className="text-gray-500">Aucun email non lu</p>
          </div>
        ) : (
          <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>
            ))}
            
            {mailUrl && (
              <div className="pt-2">
                <Link href={mailUrl} className="text-sm text-blue-600 hover:text-blue-800">
                  Voir tous les emails →
                </Link>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 