'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 account for now since we're using IMAP
  const [accounts] = useState<Account[]>([
    { id: 1, name: 'Work', email: 'contact@governance-labs.org', color: 'bg-blue-500' }
  ]);

  const [emails, setEmails] = useState<Email[]>([]);
  const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [selectedAccount] = useState(1); // Only one account for now
  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);

  // 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

  // Fetch mailboxes from IMAP API
  useEffect(() => {
    async function fetchMailboxes() {
      try {
        const res = await fetch('/api/mail', { method: 'POST' });
        if (!res.ok) {
          throw new Error('Failed to fetch mailboxes');
        }
        const data = await res.json();
        if (data.error) {
          throw new Error(data.error);
        }
        setMailboxes(data.mailboxes || []);
      } catch (error) {
        console.error('Error fetching mailboxes:', error);
      }
    }

    fetchMailboxes();
  }, []);

  // Filter emails based on current view
  const filteredEmails = emails.filter(email => 
    currentView === 'starred' ? email.starred : email.category === currentView
  );

  // Handle email selection
  const handleEmailClick = (emailId: number) => {
    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();
    // TODO: Implement IMAP flag toggle
    const updatedEmails = emails.map(email => 
      email.id === emailId ? { ...email, starred: !email.starred } : email
    );
    setEmails(updatedEmails);
  };

  // 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 selected email
  const getSelectedEmail = () => {
    return emails.find(email => email.id === selectedEmail);
  };

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

  // 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 () => {
    // TODO: Implement IMAP delete
    if (deleteType === 'email' && itemToDelete) {
      setEmails(emails.filter(email => email.id !== itemToDelete));
      setSelectedEmail(null);
    } else if (deleteType === 'emails') {
      setEmails(emails.filter(email => !selectedEmails.includes(email.id)));
      setSelectedEmails([]);
      setShowBulkActions(false);
    }
    setShowDeleteConfirm(false);
  };

  // Modified account action handler
  const handleAccountAction = (accountId: number, action: 'edit' | 'delete') => {
    setShowAccountActions(null);
    if (action === 'delete') {
      setDeleteType('account');
      setItemToDelete(accountId);
      setShowDeleteConfirm(true);
    }
  };

  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-100 text-gray-900 overflow-hidden mt-12">
      {/* Sidebar */}
      <div className={`${sidebarOpen ? 'w-72' : 'w-20'} bg-white border-r border-gray-200 flex flex-col transition-all duration-300 ease-in-out
                    ${mobileSidebarOpen ? 'fixed inset-y-0 left-0 z-40' : 'hidden'} md:block`}>
        {/* Logo and toggle */}
        <div className="p-4 flex items-center justify-between border-b border-gray-200">
          {sidebarOpen && <h1 className="text-base font-medium text-gray-900">Mail</h1>}
          <Button 
            variant="ghost"
            size="icon"
            className="hidden md:flex hover:bg-gray-100"
            onClick={() => setSidebarOpen(!sidebarOpen)}
          >
            {sidebarOpen ? <ChevronLeft className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          </Button>
        </div>

        {/* Compose button */}
        <div className="p-4">
          <Button
            className="w-full justify-start gap-2 bg-gray-900 text-white hover:bg-gray-800"
            onClick={() => setComposeOpen(true)}
          >
            <Plus className="h-4 w-4" />
            {sidebarOpen && "Compose"}
          </Button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto">
          <div className="space-y-1 px-2">
            <Button
              variant={currentView === 'inbox' ? 'secondary' : 'ghost'}
              className="w-full justify-start gap-2 py-2 px-3 text-sm font-medium"
              onClick={() => setCurrentView('inbox')}
            >
              <Inbox className="h-4 w-4" />
              {sidebarOpen && "Inbox"}
            </Button>
            <Button
              variant={currentView === 'starred' ? 'secondary' : 'ghost'}
              className="w-full justify-start gap-2 py-2 px-3 text-sm font-medium"
              onClick={() => setCurrentView('starred')}
            >
              <Star className="h-4 w-4" />
              {sidebarOpen && "Starred"}
            </Button>
            <Button
              variant={currentView === 'sent' ? 'secondary' : 'ghost'}
              className="w-full justify-start gap-2 py-2 px-3 text-sm font-medium"
              onClick={() => setCurrentView('sent')}
            >
              <Send className="h-4 w-4" />
              {sidebarOpen && "Sent"}
            </Button>
            <Button
              variant={currentView === 'trash' ? 'secondary' : 'ghost'}
              className="w-full justify-start gap-2 py-2 px-3 text-sm font-medium"
              onClick={() => setCurrentView('trash')}
            >
              <Trash className="h-4 w-4" />
              {sidebarOpen && "Trash"}
            </Button>
          </div>

          {/* IMAP Folders */}
          {mailboxes.length > 0 && (
            <div className="mt-6">
              <div className="px-3 mb-2">
                <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Folders
                </h2>
              </div>
              <div className="space-y-1 px-2">
                {mailboxes.map((mailbox) => (
                  <Button
                    key={mailbox.path}
                    variant={currentView === mailbox.path ? 'secondary' : 'ghost'}
                    className="w-full justify-start gap-2 py-2 px-3 text-sm font-medium"
                    onClick={() => setCurrentView(mailbox.path)}
                  >
                    <Folder className="h-4 w-4" />
                    {sidebarOpen && mailbox.name}
                  </Button>
                ))}
              </div>
            </div>
          )}
        </nav>

        {/* Account info */}
        <div className="p-4 border-t border-gray-200">
          <div className="flex items-center gap-3">
            <Avatar className="h-8 w-8">
              <AvatarFallback className={accounts[0].color}>
                {accounts[0].email.charAt(0).toUpperCase()}
              </AvatarFallback>
            </Avatar>
            {sidebarOpen && (
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-gray-900 truncate">
                  {accounts[0].name}
                </p>
                <p className="text-xs text-gray-500 truncate">
                  {accounts[0].email}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        {/* Header */}
        <header className="bg-white border-b border-gray-200 px-4 py-3">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="icon"
              className="md:hidden"
              onClick={() => setMobileSidebarOpen(true)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
            <div className="flex-1 flex items-center gap-4">
              <div className="relative flex-1 max-w-2xl">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  type="search"
                  placeholder="Search emails..."
                  className="pl-10 bg-gray-50 border-gray-200"
                />
              </div>
              <Button
                variant="ghost"
                size="icon"
                className="hidden md:flex"
              >
                <Settings className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </header>

        {/* Email list */}
        <div className="flex-1 overflow-y-auto bg-white">
          {filteredEmails.length > 0 ? (
            <div className="divide-y divide-gray-100">
              {filteredEmails.map((email) => (
                <div
                  key={email.id}
                  className={`group flex items-center gap-4 px-4 py-3 cursor-pointer hover:bg-gray-50
                    ${email.read ? 'bg-white' : 'bg-gray-50'}`}
                  onClick={() => handleEmailClick(email.id)}
                >
                  <Checkbox
                    checked={selectedEmails.includes(email.id)}
                    onClick={(e) => toggleEmailSelection(email.id, e)}
                    className="h-4 w-4"
                  />
                  <button
                    onClick={(e) => toggleStarred(email.id, e)}
                    className={`text-gray-400 hover:text-yellow-400
                      ${email.starred ? 'text-yellow-400' : ''}`}
                  >
                    <Star className="h-4 w-4" />
                  </button>
                  <div className={`flex-1 min-w-0 ${!email.read ? 'font-medium' : ''}`}>
                    <div className="flex items-center gap-2">
                      <div className={`h-2 w-2 rounded-full ${getAccountColor(email.accountId)}`} />
                      <span className="truncate">{email.fromName}</span>
                    </div>
                    <div className="flex items-center gap-2 text-sm text-gray-600">
                      <span className="truncate">{email.subject}</span>
                      <span className="whitespace-nowrap">{formatDate(email.date)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <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>
      </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>
  );
}