"use client";

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

interface Email {
  id: string;
  subject: string;
  sender: {
    name: string;
    email: string;
  };
  date: string;
  isUnread: boolean;
}

export function Email() {
  const [emails, setEmails] = useState<Email[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const { status } = useSession();

  const fetchEmails = async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    setLoading(true);
    
    // Placeholder data - replace with actual API call
    const mockEmails = [
      { 
        id: '1', 
        subject: 'Project Update: Q1 Milestones', 
        sender: { name: 'Project Manager', email: 'pm@example.com' },
        date: '2024-03-20 09:30',
        isUnread: true
      },
      { 
        id: '2', 
        subject: 'Team Meeting Notes', 
        sender: { name: 'Team Lead', email: 'lead@example.com' },
        date: '2024-03-19 15:45',
        isUnread: false
      },
      { 
        id: '3', 
        subject: 'Important: System Maintenance', 
        sender: { name: 'IT Support', email: 'it@example.com' },
        date: '2024-03-19 11:20',
        isUnread: true
      },
    ];
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      setEmails(mockEmails);
      setError(null);
    } catch (err) {
      setError('Failed to fetch emails');
      console.error('Error fetching emails:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    if (status === 'authenticated') {
      fetchEmails();
    }
  }, [status]);

  if (status === 'loading' || loading) {
    return (
      <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg 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">Email</CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <p className="text-center text-gray-500">Loading...</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
      <CardHeader className="flex flex-row items-center justify-between pb-2 space-x-4 border-b border-gray-100">
        <CardTitle className="text-lg font-semibold text-gray-800">Email</CardTitle>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => fetchEmails(true)}
          disabled={refreshing}
          className={`${refreshing ? 'animate-spin' : ''} text-gray-600 hover:text-gray-900`}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="p-3">
        {error ? (
          <p className="text-center text-red-500">{error}</p>
        ) : (
          <div className="space-y-2 max-h-[220px] overflow-y-auto">
            {emails.length === 0 ? (
              <p className="text-center text-gray-500">No emails available</p>
            ) : (
              emails.map((email) => (
                <div
                  key={email.id}
                  className="p-2 hover:bg-gray-50/50 rounded-lg transition-colors"
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm text-gray-600">{email.sender.name}</span>
                    <div className="flex items-center space-x-2">
                      {email.isUnread && (
                        <span className="w-1.5 h-1.5 bg-blue-600 rounded-full"></span>
                      )}
                      <span className="text-sm text-gray-500">{email.date}</span>
                    </div>
                  </div>
                  <h3 className={`text-sm ${email.isUnread ? 'font-semibold' : 'font-medium'} text-gray-800 line-clamp-2`}>
                    {email.subject}
                  </h3>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 