'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: string;
  accountId: string;
  from: string;
  fromName?: string;
  to: string;
  subject: string;
  body: string;
  preview: string;
  category: string;
  date: Date;
  read: boolean;
  starred: boolean;
}

// Improved MIME Decoder Implementation for Infomaniak
function extractBoundary(headers: string): string | null {
  const boundaryMatch = headers.match(/boundary="?([^"\r\n;]+)"?/i) || 
                       headers.match(/boundary=([^\r\n;]+)/i);
  
  return boundaryMatch ? boundaryMatch[1].trim() : null;
}

function decodeQuotedPrintable(text: string, charset: string): string {
  if (!text) return '';
  
  // Replace soft line breaks (=\r\n or =\n or =\r)
  let decoded = text.replace(/=(?:\r\n|\n|\r)/g, '');
  
  // Replace quoted-printable encoded characters (including non-ASCII characters)
  decoded = decoded.replace(/=([0-9A-F]{2})/gi, (match, p1) => {
    return String.fromCharCode(parseInt(p1, 16));
  });
  
  // Handle character encoding
  try {
    // For browsers with TextDecoder support
    if (typeof TextDecoder !== 'undefined') {
      // Convert string to array of byte values
      const bytes = new Uint8Array(Array.from(decoded).map(c => c.charCodeAt(0)));
      return new TextDecoder(charset).decode(bytes);
    }
    
    // Fallback for older browsers or when charset handling is not critical
    return decoded;
  } catch (e) {
    console.warn('Charset conversion error:', e);
    return decoded;
  }
}

function parseFullEmail(emailRaw: string) {
  // Check if this is a multipart message by looking for boundary definition
  const boundaryMatch = emailRaw.match(/boundary="?([^"\r\n;]+)"?/i) || 
                       emailRaw.match(/boundary=([^\r\n;]+)/i);
  
  if (boundaryMatch) {
    const boundary = boundaryMatch[1].trim();
    
    // Check if there's a preamble before the first boundary
    let mainHeaders = '';
    let mainContent = emailRaw;
    
    // Extract the headers before the first boundary if they exist
    const firstBoundaryPos = emailRaw.indexOf('--' + boundary);
    if (firstBoundaryPos > 0) {
      const headerSeparatorPos = emailRaw.indexOf('\r\n\r\n');
      if (headerSeparatorPos > 0 && headerSeparatorPos < firstBoundaryPos) {
        mainHeaders = emailRaw.substring(0, headerSeparatorPos);
      }
    }
    
    return processMultipartEmail(emailRaw, boundary, mainHeaders);
  } else {
    // This is a single part message
    return processSinglePartEmail(emailRaw);
  }
}

function processMultipartEmail(emailRaw: string, boundary: string, mainHeaders: string = ''): { 
  text: string; 
  html: string; 
  attachments: { filename: string; contentType: string; encoding: string; content: string; }[];
  headers?: string;
} {
  const result = {
    text: '',
    html: '',
    attachments: [] as { filename: string; contentType: string; encoding: string; content: string; }[],
    headers: mainHeaders
  };
  
  // Split by boundary (more robust pattern)
  const boundaryRegex = new RegExp(`--${boundary}(?:--)?(\\r?\\n|$)`, 'g');
  
  // Get all boundary positions
  const matches = Array.from(emailRaw.matchAll(boundaryRegex));
  const boundaryPositions = matches.map(match => match.index!);
  
  // Extract content between boundaries
  for (let i = 0; i < boundaryPositions.length - 1; i++) {
    const startPos = boundaryPositions[i] + matches[i][0].length;
    const endPos = boundaryPositions[i + 1];
    
    if (endPos > startPos) {
      const partContent = emailRaw.substring(startPos, endPos).trim();
      
      if (partContent) {
        const decoded = processSinglePartEmail(partContent);
        
        if (decoded.contentType.includes('text/plain')) {
          result.text = decoded.text || '';
        } else if (decoded.contentType.includes('text/html')) {
          result.html = cleanHtml(decoded.html || '');
        } else if (
          decoded.contentType.startsWith('image/') || 
          decoded.contentType.startsWith('application/')
        ) {
          const filename = extractFilename(partContent);
          result.attachments.push({
            filename,
            contentType: decoded.contentType,
            encoding: decoded.raw?.headers ? parseEmailHeaders(decoded.raw.headers).encoding : '7bit',
            content: decoded.raw?.body || ''
          });
        }
      }
    }
  }
  
  return result;
}

function processSinglePartEmail(rawEmail: string) {
  // Split headers and body
  const headerBodySplit = rawEmail.split(/\r?\n\r?\n/);
  const headers = headerBodySplit[0];
  const body = headerBodySplit.slice(1).join('\n\n');
  
  // Parse headers to get content type, encoding, etc.
  const emailInfo = parseEmailHeaders(headers);
  
  // Decode the body based on its encoding
  const decodedBody = decodeMIME(body, emailInfo.encoding, emailInfo.charset);
  
  return {
    subject: extractHeader(headers, 'Subject'),
    from: extractHeader(headers, 'From'),
    to: extractHeader(headers, 'To'),
    date: extractHeader(headers, 'Date'),
    contentType: emailInfo.contentType,
    text: emailInfo.contentType.includes('html') ? null : decodedBody,
    html: emailInfo.contentType.includes('html') ? decodedBody : null,
    raw: {
      headers,
      body
    }
  };
}

function extractHeader(headers: string, headerName: string): string {
  const regex = new RegExp(`^${headerName}:\\s*(.+?)(?:\\r?\\n(?!\\s)|$)`, 'im');
  const match = headers.match(regex);
  return match ? match[1].trim() : '';
}

function extractFilename(headers: string): string {
  const filenameMatch = headers.match(/filename="?([^"\r\n;]+)"?/i);
  return filenameMatch ? filenameMatch[1].trim() : 'attachment';
}

function parseEmailHeaders(headers: string): { contentType: string; encoding: string; charset: string } {
  const result = {
    contentType: 'text/plain',
    encoding: '7bit',
    charset: 'utf-8'
  };
  
  // Extract content type and charset
  const contentTypeMatch = headers.match(/Content-Type:\s*([^;]+)(?:;\s*charset=([^;"\r\n]+)|(?:;\s*charset="([^"]+)"))?/i);
  if (contentTypeMatch) {
    result.contentType = contentTypeMatch[1].trim().toLowerCase();
    if (contentTypeMatch[2]) {
      result.charset = contentTypeMatch[2].trim().toLowerCase();
    } else if (contentTypeMatch[3]) {
      result.charset = contentTypeMatch[3].trim().toLowerCase();
    }
  }
  
  // Extract content transfer encoding
  const encodingMatch = headers.match(/Content-Transfer-Encoding:\s*([^\s;\r\n]+)/i);
  if (encodingMatch) {
    result.encoding = encodingMatch[1].trim().toLowerCase();
  }
  
  return result;
}

function decodeMIME(text: string, encoding?: string, charset: string = 'utf-8'): string {
  if (!text) return '';
  
  // Normalize encoding and charset
  encoding = (encoding || '').toLowerCase();
  charset = (charset || 'utf-8').toLowerCase();
  
  try {
    // Handle different encoding types
    if (encoding === 'quoted-printable') {
      return decodeQuotedPrintable(text, charset);
    } else if (encoding === 'base64') {
      return decodeBase64(text, charset);
    } else if (encoding === '7bit' || encoding === '8bit' || encoding === 'binary') {
      // For these encodings, we still need to handle the character set
      return convertCharset(text, charset);
    } else {
      // Unknown encoding, return as is but still handle charset
      return convertCharset(text, charset);
    }
  } catch (error) {
    console.error('Error decoding MIME:', error);
    return text;
  }
}

function decodeBase64(text: string, charset: string): string {
  const cleanText = text.replace(/\s/g, '');
  
  let binaryString;
  try {
    binaryString = atob(cleanText);
  } catch (e) {
    console.error('Base64 decoding error:', e);
    return text;
  }
  
  return convertCharset(binaryString, charset);
}

function convertCharset(text: string, fromCharset: string): string {
  try {
    if (typeof TextDecoder !== 'undefined') {
      const bytes = new Uint8Array(text.length);
      for (let i = 0; i < text.length; i++) {
        bytes[i] = text.charCodeAt(i) & 0xFF;
      }
      
      let normalizedCharset = fromCharset.toLowerCase();
      
      // Normalize charset names
      if (normalizedCharset === 'iso-8859-1' || normalizedCharset === 'latin1') {
        normalizedCharset = 'iso-8859-1';
      } else if (normalizedCharset === 'windows-1252' || normalizedCharset === 'cp1252') {
        normalizedCharset = 'windows-1252';
      }
      
      const decoder = new TextDecoder(normalizedCharset);
      return decoder.decode(bytes);
    }
    
    // Fallback for older browsers or unsupported charsets
    if (fromCharset.toLowerCase() === 'iso-8859-1' || fromCharset.toLowerCase() === 'windows-1252') {
      return text
        .replace(/\xC3\xA0/g, 'à')
        .replace(/\xC3\xA2/g, 'â')
        .replace(/\xC3\xA9/g, 'é')
        .replace(/\xC3\xA8/g, 'è')
        .replace(/\xC3\xAA/g, 'ê')
        .replace(/\xC3\xAB/g, 'ë')
        .replace(/\xC3\xB4/g, 'ô')
        .replace(/\xC3\xB9/g, 'ù')
        .replace(/\xC3\xBB/g, 'û')
        .replace(/\xC3\x80/g, 'À')
        .replace(/\xC3\x89/g, 'É')
        .replace(/\xC3\x87/g, 'Ç')
        .replace(/\xC2\xA0/g, ' ');
    }
    
    return text;
  } catch (e) {
    console.error('Character set conversion error:', e, 'charset:', fromCharset);
    return text;
  }
}

function extractHtmlBody(htmlContent: string): string {
  const bodyMatch = htmlContent.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
  return bodyMatch ? bodyMatch[1] : htmlContent;
}

function cleanHtml(html: string): string {
  if (!html) return '';
  
  return html
    // Fix common Infomaniak-specific character encodings
    .replace(/=C2=A0/g, ' ')  // non-breaking space
    .replace(/=E2=80=93/g, '\u2013')  // en dash
    .replace(/=E2=80=94/g, '\u2014')  // em dash
    .replace(/=E2=80=98/g, '\u2018')  // left single quote
    .replace(/=E2=80=99/g, '\u2019')  // right single quote
    .replace(/=E2=80=9C/g, '\u201C')  // left double quote
    .replace(/=E2=80=9D/g, '\u201D')  // right double quote
    .replace(/=C3=A0/g, 'à')
    .replace(/=C3=A2/g, 'â')
    .replace(/=C3=A9/g, 'é')
    .replace(/=C3=A8/g, 'è')
    .replace(/=C3=AA/g, 'ê')
    .replace(/=C3=AB/g, 'ë')
    .replace(/=C3=B4/g, 'ô')
    .replace(/=C3=B9/g, 'ù')
    .replace(/=C3=BB/g, 'û')
    .replace(/=C3=80/g, 'À')
    .replace(/=C3=89/g, 'É')
    .replace(/=C3=87/g, 'Ç')
    // Clean up HTML entities
    .replace(/&Atilde;&sect;/g, 'ç')
    .replace(/&Atilde;&copy;/g, 'é')
    .replace(/&Atilde;&uml;/g, 'ë')
    .replace(/&Atilde;&ordf;/g, 'ª')
    .replace(/&Atilde;&laquo;/g, '«')
    .replace(/&Atilde;&raquo;/g, '»')
    .replace(/&nbsp;/g, ' ')
    .replace(/\xA0/g, ' ');
}

function decodeMimeContent(content: string): string {
  if (!content) return '';

  // Check if this is an Infomaniak multipart message
  if (content.includes('Content-Type: multipart/')) {
    const boundary = content.match(/boundary="([^"]+)"/)?.[1];
    if (boundary) {
      const parts = content.split('--' + boundary);
      let htmlContent = '';
      let textContent = '';

      parts.forEach(part => {
        if (part.includes('Content-Type: text/html')) {
          const match = part.match(/\r?\n\r?\n([\s\S]+?)(?=\r?\n--)/);
          if (match) {
            htmlContent = cleanHtml(match[1]);
          }
        } else if (part.includes('Content-Type: text/plain')) {
          const match = part.match(/\r?\n\r?\n([\s\S]+?)(?=\r?\n--)/);
          if (match) {
            textContent = cleanHtml(match[1]);
          }
        }
      });

      // Prefer HTML content if available
      return htmlContent || textContent;
    }
  }

  // If not multipart or no boundary found, clean the content directly
  return cleanHtml(content);
}

export default function MailPage() {
  // Single IMAP account for now
  const [accounts, setAccounts] = useState<Account[]>([
    { id: 1, name: 'Mail', email: 'alma@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<Email | 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<string[]>([]);
  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(false);
  const [error, setError] = useState<string | null>(null);
  const [composeSubject, setComposeSubject] = useState('');
  const [composeRecipient, setComposeRecipient] = useState('');
  const [composeContent, setComposeContent] = useState('');

  // Fetch emails from IMAP API
  const loadEmails = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/mail');
      if (!response.ok) {
        throw new Error('Failed to fetch emails');
      }
      const data = await response.json();
      console.log('API Response:', data); // Debug log
      
      // Handle different possible response formats
      let emailData = [];
      if (Array.isArray(data)) {
        emailData = data;
      } else if (data && typeof data === 'object') {
        // If data is an object, try to extract emails from it
        if (data.emails) {
          emailData = data.emails;
        } else if (data.messages) {
          emailData = data.messages;
        } else {
          // Try to convert object values to array
          emailData = Object.values(data);
        }
      }
      
      console.log('Processed email data:', emailData); // Debug log
      
      // Ensure all dates are Date objects and add required properties
      const processedEmails = emailData.map((email: any) => ({
        id: email.id || email.uid || email.messageId || Math.random().toString(),
        accountId: email.accountId || '1',
        from: email.from || '',
        fromName: email.fromName || email.from?.split('@')[0] || '',
        to: email.to || '',
        subject: email.subject || '(No Subject)',
        body: email.body || email.text || email.html || '',
        preview: email.preview || email.body?.substring(0, 100) || '',
        category: email.category || 'inbox',
        date: email.date ? new Date(email.date) : new Date(),
        read: email.read || false,
        starred: email.starred || false
      }));
      
      console.log('Final processed emails:', processedEmails); // Debug log
      setEmails(processedEmails);
    } catch (err) {
      console.error('Error fetching emails:', err);
      setError(err instanceof Error ? err.message : 'An error occurred');
      setEmails([]);
    } finally {
      setLoading(false);
    }
  };

  // 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 current view
  const filteredEmails = emails.filter(email => {
    if (selectedAccount === 0) return true;
    // Use the email address to match instead of accountId
    const selectedAccountEmail = accounts.find(acc => acc.id === selectedAccount)?.email;
    return email.from === selectedAccountEmail || email.to === selectedAccountEmail;
  }).filter(email => {
    switch (currentView) {
      case "inbox":
        return email.category === "inbox";
      case "starred":
        return email.starred;
      case "sent":
        return email.category === "sent";
      case "trash":
        return email.category === "trash";
      default:
        return true;
    }
  });

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

  // Update email click handler to work without mark-read endpoint
  const handleEmailSelect = (email: Email) => {
    setSelectedEmail(selectedEmail?.id === email.id ? null : email);
  };

  // Toggle starred status
  const toggleStarred = async (emailId: string, 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: string, 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.toString()] })
        });
        setEmails(emails.filter(email => email.id !== itemToDelete.toString()));
        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?.id);
  };

  // Add useEffect to load emails on mount
  useEffect(() => {
    loadEmails();
  }, []);

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

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

  const handleEmailCheckbox = (e: React.ChangeEvent<HTMLInputElement>, emailId: string) => {
    e.stopPropagation();
    if (e.target.checked) {
      setSelectedEmails([...selectedEmails, emailId]);
    } else {
      setSelectedEmails(selectedEmails.filter(id => id !== emailId));
    }
  };

  // Handle reply
  const handleReply = async (type: 'reply' | 'replyAll' | 'forward') => {
    const selectedEmailData = getSelectedEmail();
    if (!selectedEmailData) return;

    setComposeOpen(true);
    const subject = `${type === 'forward' ? 'Fwd: ' : 'Re: '}${selectedEmailData.subject}`;
    let to = '';
    let content = '';

    switch (type) {
      case 'reply':
        to = selectedEmailData.from;
        content = `\n\nOn ${new Date(selectedEmailData.date).toLocaleString()}, ${selectedEmailData.fromName} wrote:\n> ${selectedEmailData.body.split('\n').join('\n> ')}`;
        break;
      case 'replyAll':
        to = selectedEmailData.from; // You would also need to add CC recipients here
        content = `\n\nOn ${new Date(selectedEmailData.date).toLocaleString()}, ${selectedEmailData.fromName} wrote:\n> ${selectedEmailData.body.split('\n').join('\n> ')}`;
        break;
      case 'forward':
        content = `\n\n---------- Forwarded message ----------\nFrom: ${selectedEmailData.fromName} <${selectedEmailData.from}>\nDate: ${new Date(selectedEmailData.date).toLocaleString()}\nSubject: ${selectedEmailData.subject}\n\n${selectedEmailData.body}`;
        break;
    }

    setComposeSubject(subject);
    setComposeRecipient(to);
    setComposeContent(content);
  };

  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">
            <Mail className="h-6 w-6 text-gray-600" />
            <span className="text-xl font-semibold text-gray-900">COURRIER</span>
          </div>
        </div>

        {/* Compose button */}
        <div className="p-3 border-b border-gray-100">
          <Button 
            className="w-full bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center transition-all py-2"
            onClick={() => setComposeOpen(true)}
          >
            <div className="flex items-center">
              <PlusIcon className="h-4 w-4" />
              <span className="ml-2">Compose</span>
            </div>
          </Button>
        </div>

        {/* Accounts Section with Scrollable Content */}
        <div className="flex flex-col min-h-0 flex-1">
          <div className="p-3 border-b border-gray-100">
            <Button 
              variant="ghost"
              className="w-full justify-between mb-2 text-sm font-medium text-gray-500"
              onClick={() => setAccountsDropdownOpen(!accountsDropdownOpen)}
            >
              <span>Accounts</span>
              {accountsDropdownOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
            </Button>
            
            {accountsDropdownOpen && (
              <div className="space-y-1 pl-2">
                {/* All Accounts Option */}
                <Button
                  variant="ghost"
                  className="w-full justify-start px-2 py-1.5 text-sm"
                  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 group"
                      onClick={() => setSelectedAccount(account.id)}
                    >
                      <div className="flex flex-col items-start">
                        <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>
                        <span className="text-xs text-gray-500 ml-4">{account.email}</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>
            )}
          </div>

          {/* Scrollable Navigation */}
          <div className="overflow-y-auto flex-1">
            <nav className="p-3">
              {/* Navigation items */}
              <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>
        </div>
      </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 */}
          <div className="flex flex-col flex-1 overflow-hidden">
            <div className="flex-1 overflow-auto">
              {loading ? (
                <div className="flex items-center justify-center h-full">
                  <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
                  <span className="ml-3 text-gray-600">Loading emails...</span>
                </div>
              ) : error ? (
                <div className="flex flex-col items-center justify-center h-full">
                  <div className="text-red-500 mb-4">Error loading emails</div>
                  <button
                    onClick={() => loadEmails()}
                    className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
                  >
                    Try Again
                  </button>
                </div>
              ) : emails.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full">
                  <div className="text-gray-500 mb-4">No emails found</div>
                </div>
              ) : (
                <ul className="divide-y divide-gray-200">
                  {filteredEmails.map((email) => (
                    <li
                      key={email.id}
                      className={`flex items-center p-4 hover:bg-gray-50 transition-colors duration-150 cursor-pointer ${
                        selectedEmail?.id === email.id ? 'bg-blue-50' : ''
                      } ${!email.read ? 'bg-blue-50/20' : ''}`}
                      onClick={() => handleEmailSelect(email)}
                    >
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between space-x-4">
                          <div className="flex items-center space-x-4 flex-1">
                            <input
                              type="checkbox"
                              checked={selectedEmails.includes(email.id)}
                              onChange={(e) => handleEmailCheckbox(e, email.id)}
                              onClick={(e) => e.stopPropagation()}
                              className="h-4 w-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                            />
                            <div className="min-w-0 flex-1">
                              <p className={`text-sm truncate ${!email.read ? 'font-semibold' : 'font-medium'} text-gray-900`}>
                                {email.fromName || email.from}
                              </p>
                              <div className="flex items-center space-x-2">
                                <p className={`text-sm truncate ${!email.read ? 'font-medium' : ''} text-gray-600 flex-1`}>
                                  {email.subject}
                                </p>
                                <span className="text-xs text-gray-500 whitespace-nowrap">
                                  {formatDate(email.date.toISOString())}
                                </span>
                              </div>
                            </div>
                          </div>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              toggleStarred(email.id, e);
                            }}
                            className="text-gray-400 hover:text-yellow-400 transition-colors duration-150 p-1 hover:bg-gray-100 rounded-full"
                          >
                            {email.starred ? (
                              <Star className="h-5 w-5 text-yellow-400" />
                            ) : (
                              <Star className="h-5 w-5" />
                            )}
                          </button>
                        </div>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
        </div>

        {/* Email preview panel */}
        <div className="flex-1 bg-white/95 backdrop-blur-sm overflow-y-auto">
          {selectedEmail ? (
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-gray-900">{selectedEmail.subject}</h2>
                <div className="flex items-center gap-2">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-400 hover:text-gray-900"
                    onClick={() => handleReply('reply')}
                  >
                    <Reply className="h-5 w-5" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-400 hover:text-gray-900"
                    onClick={() => handleReply('replyAll')}
                  >
                    <ReplyAll className="h-5 w-5" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-400 hover:text-gray-900"
                    onClick={() => handleReply('forward')}
                  >
                    <Forward className="h-5 w-5" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-400 hover:text-gray-900"
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleStarred(selectedEmail.id, e);
                    }}
                  >
                    {selectedEmail.starred ? (
                      <Star className="h-5 w-5 text-yellow-400" />
                    ) : (
                      <Star className="h-5 w-5" />
                    )}
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-gray-400 hover:text-gray-900"
                    onClick={() => {
                      setDeleteType('email');
                      setItemToDelete(parseInt(selectedEmail.id));
                      setShowDeleteConfirm(true);
                    }}
                  >
                    <Trash2 className="h-5 w-5" />
                  </Button>
                </div>
              </div>

              <div className="flex items-center gap-4 mb-6">
                <Avatar className="h-10 w-10">
                  <AvatarFallback>
                    {selectedEmail.fromName?.charAt(0) || selectedEmail.from.charAt(0)}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <p className="font-medium text-gray-900">
                    {selectedEmail.fromName || selectedEmail.from}
                  </p>
                  <p className="text-sm text-gray-500">
                    to {selectedEmail.to}
                  </p>
                </div>
                <div className="ml-auto text-sm text-gray-500">
                  {formatDate(selectedEmail.date.toISOString())}
                </div>
              </div>

              <div className="prose max-w-none">
                {selectedEmail.body}
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-full">
              <Mail className="h-12 w-12 text-gray-400 mb-4" />
              <p className="text-gray-500">Select an email to view its contents</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}