'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 { Label } from "@/components/ui/label";
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, Paperclip, MessageSquare } 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;
}

// Add MIME decoding function
const decodeMimeContent = (content: string) => {
  try {
    // Remove MIME headers
    const contentWithoutHeaders = content.replace(/^.*?Content-Type:.*?\n\n/s, '');
    
    // Decode quoted-printable
    const decoded = contentWithoutHeaders
      .replace(/=\n/g, '') // Remove soft line breaks
      .replace(/=([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
      .replace(/=C2=A0/g, ' ') // Replace non-breaking spaces
      .replace(/\[LINK: (.*?)\]/g, '$1') // Format links
      .replace(/\[IMG: (.*?)\]/g, '') // Remove image placeholders
      .trim();
    
    return decoded;
  } catch (error) {
    console.error('Error decoding MIME content:', error);
    return content;
  }
};

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

  // Mock folders data
  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)
  );

  // Format date for display
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else {
      return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
    }
  };

  // Get account color
  const getAccountColor = (accountId: number) => {
    const account = accounts.find(acc => acc.id === accountId);
    return account ? account.color : 'bg-gray-500';
  };

  // 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 bulk selection
  const toggleEmailSelection = (emailId: number, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedEmails(prev => 
      prev.includes(emailId) 
        ? prev.filter(id => id !== emailId)
        : [...prev, emailId]
    );
    setShowBulkActions(true);
  };

  // Handle select all
  const toggleSelectAll = () => {
    if (selectedEmails.length === filteredEmails.length) {
      setSelectedEmails([]);
      setShowBulkActions(false);
    } else {
      setSelectedEmails(filteredEmails.map(email => email.id));
      setShowBulkActions(true);
    }
  };

  // Handle bulk delete
  const handleBulkDelete = () => {
    setDeleteType('emails');
    setShowDeleteConfirm(true);
  };

  // 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);
  };

  // Get selected email
  const getSelectedEmail = () => {
    return emails.find(email => email.id === selectedEmail);
  };

  // Add account management functions
  const handleAddAccount = () => {
    // Implementation for adding a new account
  };

  const handleRemoveAccount = (accountId: number) => {
    setAccounts(accounts.filter(acc => acc.id !== accountId));
    if (selectedAccount === accountId) {
      setSelectedAccount(accounts[0].id);
    }
  };

  const handleEditAccount = (accountId: number, newName: string) => {
    setAccounts(accounts.map(acc => 
      acc.id === accountId ? { ...acc, name: newName } : acc
    ));
  };

  if (loading) {
    return (
      <div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
        <div className="text-center">
          <Mail className="h-12 w-12 mb-4 text-gray-400 animate-pulse mx-auto" />
          <p className="text-gray-600">Loading your emails...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
        <div className="text-center max-w-md mx-auto px-4">
          <Mail className="h-12 w-12 mb-4 text-red-400 mx-auto" />
          <p className="text-red-500 mb-4">{error}</p>
          <Button 
            variant="outline"
            onClick={() => window.location.reload()}
            className="mx-auto"
          >
            Try Again
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-[calc(100vh-theme(spacing.12))] bg-gray-50 text-gray-900 overflow-hidden mt-12">
      {/* Sidebar */}
      <div className={`${sidebarOpen ? 'w-72' : 'w-20'} bg-white/95 backdrop-blur-sm border-0 shadow-lg flex flex-col transition-all duration-300 ease-in-out
                    ${mobileSidebarOpen ? 'fixed inset-y-0 left-0 z-40' : 'hidden'} md:block`}>
        {/* Courrier Title */}
        <div className="p-3 border-b border-gray-100">
          <div className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-gray-600" />
            <span className="font-semibold text-gray-900">Courrier</span>
          </div>
        </div>

        {/* Accounts Section */}
        <div className="p-3 border-b border-gray-100">
          <div className="text-sm font-medium text-gray-500 mb-2">Accounts</div>
          
          {/* All Accounts Option */}
          <Button
            variant="ghost"
            className="w-full justify-start px-2 py-1.5 text-sm mb-1"
            onClick={() => setSelectedAccount(0)}
          >
            <div className="flex items-center gap-2 w-full">
              <div className="w-2.5 h-2.5 rounded-full bg-gray-400"></div>
              <span className="font-medium">All</span>
            </div>
          </Button>

          {/* Mail Accounts List */}
          {accounts.map(account => (
            <div key={account.id} className="relative group">
              <Button
                variant="ghost"
                className="w-full justify-between px-2 py-1.5 text-sm mb-1 group"
                onClick={() => setSelectedAccount(account.id)}
              >
                <div className="flex items-center gap-2">
                  <div className={`w-2.5 h-2.5 rounded-full ${account.color}`}></div>
                  <span className="font-medium">{account.name}</span>
                </div>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity"
                  onClick={(e) => {
                    e.stopPropagation();
                    setShowAccountActions(account.id);
                  }}
                >
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </Button>

              {/* Account Actions Dropdown */}
              {showAccountActions === account.id && (
                <div className="absolute right-0 mt-1 w-48 bg-white rounded-md shadow-lg py-1 z-10">
                  <button
                    className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                    onClick={() => {
                      const newName = prompt('Enter new account name:', account.name);
                      if (newName) handleEditAccount(account.id, newName);
                      setShowAccountActions(null);
                    }}
                  >
                    <Edit className="h-4 w-4 inline-block mr-2" />
                    Modify Account
                  </button>
                  <button
                    className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100"
                    onClick={() => {
                      setDeleteType('account');
                      setItemToDelete(account.id);
                      setShowDeleteConfirm(true);
                      setShowAccountActions(null);
                    }}
                  >
                    <Trash2 className="h-4 w-4 inline-block mr-2" />
                    Remove Account
                  </button>
                </div>
              )}
            </div>
          ))}

          {/* Add Account Button */}
          <Button
            variant="ghost"
            className="w-full justify-start px-2 py-1.5 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50"
            onClick={handleAddAccount}
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Account
          </Button>
        </div>

        {/* Compose button */}
        <Button 
          className={`mx-3 mt-3 mb-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center transition-all ${sidebarOpen ? 'py-2 px-4' : 'p-2'}`}
          onClick={() => setComposeOpen(true)}
        >
          {sidebarOpen ? (
            <div className="flex items-center">
              <PlusIcon className="h-4 w-4" />
              <span className="ml-2">Compose</span>
            </div>
          ) : (
            <PlusIcon className="h-4 w-4" />
          )}
        </Button>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-2">
          <ul className="space-y-0.5 px-2">
            <li>
              <Button 
                variant={currentView === 'inbox' ? 'secondary' : 'ghost'}
                className={`w-full justify-start py-2 ${currentView === 'inbox' ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'}`}
                onClick={() => {setCurrentView('inbox'); setSelectedEmail(null);}}
              >
                <Inbox className="h-4 w-4 mr-2" />
                {sidebarOpen && <span>Inbox</span>}
              </Button>
            </li>
            <li>
              <Button 
                variant={currentView === 'starred' ? 'secondary' : 'ghost'}
                className={`w-full justify-start py-2 ${currentView === 'starred' ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'}`}
                onClick={() => {setCurrentView('starred'); setSelectedEmail(null);}}
              >
                <Star className="h-4 w-4 mr-2" />
                {sidebarOpen && <span>Starred</span>}
              </Button>
            </li>
            <li>
              <Button 
                variant={currentView === 'sent' ? 'secondary' : 'ghost'}
                className={`w-full justify-start py-2 ${currentView === 'sent' ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'}`}
                onClick={() => {setCurrentView('sent'); setSelectedEmail(null);}}
              >
                <Send className="h-4 w-4 mr-2" />
                {sidebarOpen && <span>Sent</span>}
              </Button>
            </li>
            <li>
              <Button 
                variant={currentView === 'trash' ? 'secondary' : 'ghost'}
                className={`w-full justify-start py-2 ${currentView === 'trash' ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'}`}
                onClick={() => {setCurrentView('trash'); setSelectedEmail(null);}}
              >
                <Trash className="h-4 w-4 mr-2" />
                {sidebarOpen && <span>Trash</span>}
              </Button>
            </li>

            {/* Folders Section */}
            <li className="mt-4">
              <Button 
                variant="ghost"
                className="w-full justify-between py-2 text-gray-600 hover:text-gray-900"
                onClick={() => setFoldersDropdownOpen(!foldersDropdownOpen)}
              >
                <div className="flex items-center">
                  <Folder className="h-4 w-4 mr-2" />
                  {sidebarOpen && <span>Folders</span>}
                </div>
                {sidebarOpen && (foldersDropdownOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />)}
              </Button>

              {/* Folders Dropdown */}
              {foldersDropdownOpen && sidebarOpen && (
                <ul className="mt-1 space-y-1">
                  {folders.map(folder => (
                    <li key={folder.id}>
                      <Button
                        variant="ghost"
                        className="w-full justify-start py-1.5 pl-8 text-sm text-gray-600 hover:text-gray-900"
                        onClick={() => {
                          setCurrentView(folder.name.toLowerCase());
                          setSelectedEmail(null);
                        }}
                      >
                        {folder.name}
                      </Button>
                    </li>
                  ))}
                </ul>
              )}
            </li>
          </ul>
        </nav>
      </div>

      {/* Main content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Email list */}
        <div className="w-[380px] bg-white/95 backdrop-blur-sm border-r border-gray-100 overflow-y-auto">
          <div className="p-4 border-b border-gray-100 flex justify-between items-center">
            <div className="flex items-center gap-4">
              {filteredEmails.length > 0 && (
                <Checkbox
                  checked={selectedEmails.length === filteredEmails.length}
                  onCheckedChange={toggleSelectAll}
                />
              )}
              <h2 className="text-lg font-semibold text-gray-800 capitalize">
                {currentView === 'starred' ? 'Starred' : currentView}
              </h2>
            </div>
            <div className="text-sm text-gray-500">
              {filteredEmails.length} emails
            </div>
          </div>

          {/* Bulk Actions Bar */}
          {showBulkActions && selectedEmails.length > 0 && (
            <div className="p-2 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
              <span className="text-sm text-gray-600">{selectedEmails.length} selected</span>
              <div className="flex items-center gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-gray-600 hover:text-gray-900"
                  onClick={() => {
                    // Handle move to folder
                  }}
                >
                  <FolderOpen className="h-4 w-4 mr-2" />
                  Move to
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-red-600 hover:text-red-700"
                  onClick={handleBulkDelete}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete
                </Button>
              </div>
            </div>
          )}

          {/* Email List */}
          {filteredEmails.length > 0 ? (
            <ul>
              {filteredEmails.map(email => (
                <li 
                  key={email.id}
                  className={`border-b border-gray-100 cursor-pointer ${email.read ? 'bg-white/95' : 'bg-blue-50/95'} hover:bg-gray-50/95`}
                  onClick={() => handleEmailClick(email.id)}
                >
                  <div className="p-4">
                    <div className="flex justify-between items-start mb-1">
                      <div className="flex items-center gap-3">
                        <Checkbox
                          checked={selectedEmails.includes(email.id)}
                          onClick={(e) => toggleEmailSelection(email.id, e)}
                        />
                        <div className="flex items-center">
                          <div className={`w-2 h-2 rounded-full ${!email.read ? 'bg-blue-600' : 'bg-transparent'} mr-2`}></div>
                          <span className={`font-medium ${!email.read ? 'font-semibold' : ''} text-gray-900`}>{email.fromName}</span>
                        </div>
                      </div>
                      <div className="text-xs text-gray-500">{formatDate(email.date)}</div>
                    </div>
                    <div className="flex justify-between items-center mb-1">
                      <h3 className={`${!email.read ? 'font-semibold' : ''} text-gray-800`}>{email.subject}</h3>
                      <Button 
                        variant="ghost"
                        size="sm"
                        className="text-gray-400 hover:text-yellow-500"
                        onClick={(e) => toggleStarred(email.id, e)}
                      >
                        <Star className="h-4 w-4" fill={email.starred ? 'currentColor' : 'none'} color={email.starred ? '#F59E0B' : 'currentColor'} />
                      </Button>
                    </div>
                    <p className="text-sm text-gray-600 truncate">
                      {decodeMimeContent(email.body)}
                    </p>
                  </div>
                </li>
              ))}
            </ul>
          ) : (
            <div className="flex flex-col items-center justify-center h-64 text-gray-500">
              <Mail className="h-12 w-12 mb-4 opacity-30" />
              <p>No emails in this folder</p>
            </div>
          )}
        </div>

        {/* Email detail view */}
        <div className="flex-1 overflow-y-auto bg-white">
          {selectedEmail ? (
            <div className="h-full flex flex-col">
              {/* Email actions header */}
              <div className="p-4 border-b border-gray-100 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                  >
                    <Reply className="h-4 w-4 mr-2" />
                    Reply
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                  >
                    <ReplyAll className="h-4 w-4 mr-2" />
                    Reply all
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                  >
                    <Forward className="h-4 w-4 mr-2" />
                    Forward
                  </Button>
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-500 hover:text-gray-700"
                    onClick={() => setShowEmailActions(!showEmailActions)}
                  >
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              {/* Email content */}
              <div className="flex-1 p-6">
                <div className="max-w-3xl mx-auto">
                  {getSelectedEmail() && (
                    <>
                      <div className="mb-6">
                        <div className="flex justify-between items-center mb-4">
                          <h1 className="text-xl font-bold">{getSelectedEmail()?.subject}</h1>
                          <Button 
                            variant="ghost"
                            size="sm"
                            className="text-gray-400 hover:text-yellow-400"
                            onClick={(e) => getSelectedEmail() && toggleStarred(getSelectedEmail()!.id, e)}
                          >
                            <Star className="h-5 w-5" fill={getSelectedEmail()?.starred ? 'currentColor' : 'none'} />
                          </Button>
                        </div>
                        
                        <div className="flex items-center">
                          <Avatar>
                            <AvatarFallback className={`${getAccountColor(getSelectedEmail()!.accountId)}`}>
                              {getSelectedEmail()?.fromName.charAt(0)}
                            </AvatarFallback>
                          </Avatar>
                          <div className="ml-3">
                            <div className="font-medium">{getSelectedEmail()?.fromName}</div>
                            <div className="text-sm text-gray-500 flex items-center">
                              <span>{getSelectedEmail()?.from}</span>
                              <span className="mx-2">•</span>
                              <span>{new Date(getSelectedEmail()!.date).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div className="border-t border-gray-200 pt-6 prose max-w-none">
                        <p>{getSelectedEmail()?.body}</p>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="h-full flex items-center justify-center">
              <div className="text-center">
                <Mail className="h-16 w-16 mx-auto mb-4 text-gray-300" />
                <p className="text-gray-500">No email selected</p>
                <p className="text-sm text-gray-400">Choose an email from the list to read its contents</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Compose email modal */}
      {composeOpen && (
        <div className="fixed inset-0 bg-black/25 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <Card className="w-full max-w-2xl bg-white max-h-[90vh] flex flex-col">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 border-b">
              <CardTitle className="text-xl">New Message</CardTitle>
              <Button 
                variant="ghost"
                size="icon"
                className="text-gray-500 hover:text-gray-700"
                onClick={() => setComposeOpen(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </CardHeader>
            <CardContent className="space-y-3 overflow-y-auto flex-1 pt-2">
              <div className="space-y-2 border-b border-gray-100 pb-3">
                <div>
                  <Label className="text-sm text-gray-700 mb-0.5">From</Label>
                  <select className="w-full bg-white border border-gray-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    {accounts.map(account => (
                      <option key={account.id} value={account.id}>
                        {account.name} ({account.email})
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <div className="flex items-center justify-between mb-0.5">
                    <Label className="text-sm text-gray-700">To</Label>
                    <div className="flex items-center gap-2">
                      {!showCc && (
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-6 text-xs text-gray-500 hover:text-gray-700"
                          onClick={() => setShowCc(true)}
                        >
                          Add Cc
                        </Button>
                      )}
                      {!showBcc && (
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-6 text-xs text-gray-500 hover:text-gray-700"
                          onClick={() => setShowBcc(true)}
                        >
                          Add Bcc
                        </Button>
                      )}
                    </div>
                  </div>
                  <Input 
                    type="email" 
                    placeholder="email@example.com" 
                    className="bg-white border-gray-200 py-1.5"
                  />
                </div>
                {showCc && (
                  <div>
                    <div className="flex items-center justify-between mb-0.5">
                      <Label className="text-sm text-gray-700">Cc</Label>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 text-xs text-gray-500 hover:text-gray-700"
                        onClick={() => setShowCc(false)}
                      >
                        Remove
                      </Button>
                    </div>
                    <Input 
                      type="email" 
                      placeholder="cc@example.com" 
                      className="bg-white border-gray-200 py-1.5"
                    />
                  </div>
                )}
                {showBcc && (
                  <div>
                    <div className="flex items-center justify-between mb-0.5">
                      <Label className="text-sm text-gray-700">Bcc</Label>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 text-xs text-gray-500 hover:text-gray-700"
                        onClick={() => setShowBcc(false)}
                      >
                        Remove
                      </Button>
                    </div>
                    <Input 
                      type="email" 
                      placeholder="bcc@example.com" 
                      className="bg-white border-gray-200 py-1.5"
                    />
                  </div>
                )}
                <div>
                  <Label className="text-sm text-gray-700 mb-0.5">Subject</Label>
                  <Input 
                    type="text" 
                    placeholder="Subject" 
                    className="bg-white border-gray-200 py-1.5"
                  />
                </div>
              </div>

              <div className="flex-1">
                <Label className="text-sm text-gray-700 mb-0.5">Message</Label>
                <Textarea 
                  className="mt-0.5 h-[calc(100%-1.5rem)] min-h-[200px] bg-white border-gray-200 resize-none"
                  placeholder="Write your message here..."
                />
              </div>

              {/* File Attachment Section */}
              <div className="border-t border-gray-100 pt-3">
                <div className="flex items-center gap-4">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="border border-gray-200 text-blue-600 hover:bg-blue-50 hover:text-blue-700"
                    onClick={() => document.getElementById('file-upload')?.click()}
                  >
                    <Paperclip className="h-4 w-4 mr-2" />
                    Attach files
                  </Button>
                  <span className="text-xs text-gray-500">Maximum file size: 25 MB</span>
                </div>
                <input
                  type="file"
                  id="file-upload"
                  multiple
                  className="hidden"
                  onChange={(e) => {
                    // Handle file upload
                    console.log(e.target.files);
                  }}
                />
              </div>

              <div className="flex justify-end gap-3 pt-3 border-t border-gray-100">
                <Button 
                  variant="ghost"
                  className="border border-gray-200 text-blue-600 hover:bg-blue-50 hover:text-blue-700"
                  onClick={() => setComposeOpen(false)}
                >
                  Cancel
                </Button>
                <Button 
                  className="bg-blue-600 text-white hover:bg-blue-700"
                  onClick={() => setComposeOpen(false)}
                >
                  Send
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you sure?</AlertDialogTitle>
            <AlertDialogDescription>
              {deleteType === 'email' && "This email will be moved to trash."}
              {deleteType === 'emails' && `${selectedEmails.length} emails will be moved to trash.`}
              {deleteType === 'account' && "This account will be permanently removed. This action cannot be undone."}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setShowDeleteConfirm(false)}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className={deleteType === 'account' ? 'bg-red-600 hover:bg-red-700' : ''}
              onClick={handleDeleteConfirm}
            >
              {deleteType === 'account' ? 'Delete Account' : 'Move to Trash'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}