'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { MoreVertical, Settings, Plus as PlusIcon, Trash2, Edit, Mail, Inbox, Send, Star, Trash, Plus, ChevronLeft, ChevronRight, Search, ChevronDown, Folder, ChevronUp, Reply, Forward, ReplyAll, MoreHorizontal, FolderOpen, X } from 'lucide-react';
import { Label } from "@/components/ui/label";
import { Paperclip, Copy, EyeOff } from 'lucide-react';

interface Account {
  id: number;
  name: string;
  email: string;
  color: string;
}

interface Email {
  id: number;
  accountId: number;
  from: string;
  fromName: string;
  to: string;
  subject: string;
  body: string;
  date: string;
  read: boolean;
  starred: boolean;
  category: string;
}

interface Mailbox {
  name: string;
  path: string;
  children?: Mailbox[];
}

export default function MailPage() {
  // Single IMAP account for now
  const [accounts, setAccounts] = useState<Account[]>([
    { id: 1, name: 'Work', email: 'contact@governance-labs.org', color: 'bg-blue-500' }
  ]);

  // State declarations
  const [selectedAccount, setSelectedAccount] = useState(1);
  const [currentView, setCurrentView] = useState('inbox');
  const [selectedEmail, setSelectedEmail] = useState<number | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
  const [composeOpen, setComposeOpen] = useState(false);
  const [accountsDropdownOpen, setAccountsDropdownOpen] = useState(false);
  const [foldersDropdownOpen, setFoldersDropdownOpen] = useState(false);
  const [showAccountActions, setShowAccountActions] = useState<number | null>(null);
  const [showEmailActions, setShowEmailActions] = useState(false);
  const [selectedEmails, setSelectedEmails] = useState<number[]>([]);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleteType, setDeleteType] = useState<'email' | 'emails' | 'account'>('email');
  const [itemToDelete, setItemToDelete] = useState<number | null>(null);
  const [showBulkActions, setShowBulkActions] = useState(false);
  const [showCc, setShowCc] = useState(false);
  const [showBcc, setShowBcc] = useState(false);
  const [emails, setEmails] = useState<Email[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch emails from IMAP API
  useEffect(() => {
    async function fetchEmails() {
      try {
        setError(null);
        setLoading(true);
        const res = await fetch('/api/mail');
        if (!res.ok) {
          throw new Error('Failed to fetch emails');
        }
        const data = await res.json();
        if (data.error) {
          throw new Error(data.error);
        }
        setEmails(data.messages || []);
      } catch (error) {
        console.error('Error fetching emails:', error);
        setError('Unable to load emails. Please try again later.');
      } finally {
        setLoading(false);
      }
    }

    fetchEmails();
  }, [currentView]); // Refetch when view changes

  // Mock folders data - will be replaced with IMAP folders later
  const folders = [
    { id: 1, name: 'Important' },
    { id: 2, name: 'Work' },
    { id: 3, name: 'Personal' },
    { id: 4, name: 'Archive' }
  ];

  // Modified accounts array with "All" option
  const allAccounts = [
    { id: 0, name: 'All', email: '', color: 'bg-gray-500' },
    ...accounts
  ];

  // Filter emails based on selected account and view
  const filteredEmails = emails.filter(email => 
    (selectedAccount === 0 || email.accountId === selectedAccount) && 
    (currentView === 'starred' ? email.starred : email.category === currentView)
  );

  // Handle email selection
  const handleEmailClick = async (emailId: number) => {
    // Mark as read in IMAP
    try {
      await fetch('/api/mail/mark-read', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ emailId })
      });
    } catch (error) {
      console.error('Error marking email as read:', error);
    }

    const updatedEmails = emails.map(email => 
      email.id === emailId ? { ...email, read: true } : email
    );
    setEmails(updatedEmails);
    setSelectedEmail(emailId);
  };

  // Toggle starred status
  const toggleStarred = async (emailId: number, e: React.MouseEvent) => {
    e.stopPropagation();
    
    // Toggle star in IMAP
    try {
      await fetch('/api/mail/toggle-star', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ emailId })
      });
    } catch (error) {
      console.error('Error toggling star:', error);
    }

    const updatedEmails = emails.map(email => 
      email.id === emailId ? { ...email, starred: !email.starred } : email
    );
    setEmails(updatedEmails);
  };

  // Handle delete confirmation
  const handleDeleteConfirm = async () => {
    try {
      if (deleteType === 'email' && itemToDelete) {
        await fetch('/api/mail/delete', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ emailIds: [itemToDelete] })
        });
        setEmails(emails.filter(email => email.id !== itemToDelete));
        setSelectedEmail(null);
      } else if (deleteType === 'emails') {
        await fetch('/api/mail/delete', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ emailIds: selectedEmails })
        });
        setEmails(emails.filter(email => !selectedEmails.includes(email.id)));
        setSelectedEmails([]);
        setShowBulkActions(false);
      }
    } catch (error) {
      console.error('Error deleting emails:', error);
    }
    setShowDeleteConfirm(false);
  };

  // Rest of the component remains exactly the same...
}