import { useEffect, useMemo, useState } from 'react';
import { IconButton } from '@/components/common/IconButton';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Icon } from '@/components/ui/icon';
import { MailboxAccountRow } from '@/features/mailboxes/components/mailbox-account-row';
import type { MailboxAccountListItem, MailboxServerListItem } from '@/features/mailboxes/types';
import { useI18n } from '@/hooks/use-i18n';
import { cn } from '@/lib/utils';

export type MailboxesDialogMode =
    | { type: 'account'; mode: 'create' | 'edit'; item?: MailboxAccountListItem; serverId?: number }
    | { type: 'server'; mode: 'create' | 'edit'; item?: MailboxServerListItem };

/** Fits ~viewport below app header + page title; inner panels scroll when content overflows. */
const WORKSPACE_SHELL_CLASS =
    'flex h-[calc(100vh-11rem)] max-h-[100vh] min-h-[24rem] flex-col overflow-hidden';

type MailboxesWorkspaceProps = {
    servers: MailboxServerListItem[];
    accounts: MailboxAccountListItem[];
    onOpenDialog: (dialog: MailboxesDialogMode) => void;
    onDeleteServer: (server: MailboxServerListItem) => void;
    onToggleActive: (account: MailboxAccountListItem, active: boolean) => void;
    onTestConnection: (account: MailboxAccountListItem) => void;
    onSync: (account: MailboxAccountListItem) => void;
    onDeleteAccount: (account: MailboxAccountListItem) => void;
};

export function MailboxesWorkspace({
    servers,
    accounts,
    onOpenDialog,
    onDeleteServer,
    onToggleActive,
    onTestConnection,
    onSync,
    onDeleteAccount,
}: MailboxesWorkspaceProps) {
    const { t } = useI18n();
    const sortedServers = useMemo(
        () => [...servers].sort((a, b) => a.name.localeCompare(b.name)),
        [servers],
    );

    const [selectedServerId, setSelectedServerId] = useState<number | null>(sortedServers[0]?.id ?? null);
    const [accountSearch, setAccountSearch] = useState('');

    useEffect(() => {
        if (sortedServers.length === 0) {
            setSelectedServerId(null);

            return;
        }

        if (selectedServerId === null || !sortedServers.some((s) => s.id === selectedServerId)) {
            setSelectedServerId(sortedServers[0].id);
        }
    }, [sortedServers, selectedServerId]);

    const selectedServer = sortedServers.find((s) => s.id === selectedServerId) ?? null;

    const serverAccounts = useMemo(() => {
        if (!selectedServer) {
            return [];
        }

        const query = accountSearch.trim().toLowerCase();

        return accounts
            .filter((a) => a.mailbox_server_id === selectedServer.id)
            .filter((a) => {
                if (query === '') {
                    return true;
                }

                return [a.name, a.email, a.client_name ?? ''].join(' ').toLowerCase().includes(query);
            })
            .sort((a, b) => {
                if (a.active !== b.active) {
                    return a.active ? -1 : 1;
                }

                return a.name.localeCompare(b.name);
            });
    }, [accounts, selectedServer, accountSearch]);

    const activeCount = serverAccounts.filter((a) => a.active).length;

    if (sortedServers.length === 0) {
        return (
            <div
                className={cn(
                    WORKSPACE_SHELL_CLASS,
                    'items-center justify-center rounded-xl border border-dashed bg-muted/20 px-6 py-16 text-center',
                )}
            >
                <div className="mb-4 flex size-14 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                    <Icon icon="solar:server-bold-duotone" className="size-7" />
                </div>
                <h3 className="text-lg font-semibold tracking-tight">{t('settings.mailboxes.workspace.no_servers_title')}</h3>
                <p className="mt-2 max-w-md text-sm text-muted-foreground">{t('settings.mailboxes.hint.add_server_first')}</p>
                <Button type="button" className="mt-6" onClick={() => onOpenDialog({ type: 'server', mode: 'create' })}>
                    <Icon icon="material-symbols:add" className="mr-1.5 size-4" />
                    {t('settings.mailboxes.actions.add_server')}
                </Button>
            </div>
        );
    }

    return (
        <div className={cn(WORKSPACE_SHELL_CLASS, 'rounded-xl border bg-card shadow-sm')}>
            <div className="flex min-h-0 flex-1 flex-col lg:flex-row">
                <aside className="flex min-h-0 w-full flex-col border-b bg-muted/25 lg:w-[280px] lg:shrink-0 lg:border-b-0 lg:border-r">
                    <div className="flex items-center justify-between gap-2 border-b px-4 py-3">
                        <div>
                            <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                                {t('settings.mailboxes.workspace.servers_label')}
                            </p>
                            <p className="text-sm font-semibold">{sortedServers.length}</p>
                        </div>
                        <IconButton
                            type="button"
                            variant="contained"
                            color="primary"
                            size="xs"
                            onClick={() => onOpenDialog({ type: 'server', mode: 'create' })}
                            icon="material-symbols:add"
                        />
                    </div>

                    <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]">
                        <nav className="flex flex-col gap-0.5 p-2" aria-label={t('settings.mailboxes.workspace.servers_label')}>
                            {sortedServers.map((server) => {
                                const isSelected = server.id === selectedServerId;
                                const count = accounts.filter((a) => a.mailbox_server_id === server.id).length;

                                return (
                                    <button
                                        key={server.id}
                                        type="button"
                                        onClick={() => {
                                            setSelectedServerId(server.id);
                                            setAccountSearch('');
                                        }}
                                        className={cn(
                                            'flex w-full flex-col gap-1 rounded-lg px-3 py-2.5 text-left transition-colors',
                                            isSelected
                                                ? 'bg-background shadow-sm ring-1 ring-border'
                                                : 'hover:bg-background/70',
                                        )}
                                    >
                                        <div className="flex items-start justify-between gap-2">
                                            <span className="truncate text-sm font-medium">{server.name}</span>
                                            <Badge variant={isSelected ? 'default' : 'secondary'} className="shrink-0 tabular-nums">
                                                {count}
                                            </Badge>
                                        </div>
                                        <span className="truncate font-mono text-[11px] text-muted-foreground">
                                            {server.host}:{server.port}
                                        </span>
                                    </button>
                                );
                            })}
                        </nav>
                    </div>
                </aside>

                <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden lg:h-full">
                    {selectedServer ? (
                        <div className="grid min-h-0 flex-1 grid-rows-[auto_auto_minmax(0,1fr)] overflow-hidden">
                            <div className="shrink-0 border-b px-4 py-4 sm:px-6">
                                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                                    <div className="min-w-0 space-y-2">
                                        <div className="flex flex-wrap items-center gap-2">
                                            <h2 className="text-lg font-semibold tracking-tight">{selectedServer.name}</h2>
                                            <Badge variant="outline" className="font-mono text-[10px] font-normal uppercase">
                                                {selectedServer.protocol}
                                            </Badge>
                                            <Badge variant="outline" className="font-mono text-[10px] font-normal uppercase">
                                                {selectedServer.encryption}
                                            </Badge>
                                        </div>
                                        <p className="font-mono text-sm text-muted-foreground">
                                            {selectedServer.host}:{selectedServer.port}
                                        </p>
                                        <p className="text-xs text-muted-foreground">
                                            {t('settings.mailboxes.workspace.inbox_folder', { folder: selectedServer.inbox_folder })}
                                        </p>
                                    </div>
                                    <div className="flex shrink-0 items-center gap-1">
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="sm"
                                            onClick={() => onOpenDialog({ type: 'server', mode: 'edit', item: selectedServer })}
                                        >
                                            <Icon icon="solar:pen-bold-duotone"  />
                                            {t('settings.mailboxes.workspace.edit_server')}
                                        </Button>
                                        <IconButton
                                            type="button"
                                            variant="text"
                                            color="danger"
                                            size="sm"
                                            disabled={selectedServer.accounts_count > 0}
                                            onClick={() => onDeleteServer(selectedServer)}
                                            icon="solar:trash-bin-trash-bold-duotone"
                                            aria-label={t('settings.mailboxes.servers_table.delete_aria')}
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="flex shrink-0 flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-6">
                                <div>
                                    <p className="text-sm font-medium">{t('settings.mailboxes.card.accounts_title')}</p>
                                    <p className="text-xs text-muted-foreground">
                                        {t('settings.mailboxes.workspace.accounts_summary', {
                                            total: serverAccounts.length,
                                            active: activeCount,
                                        })}
                                    </p>
                                </div>
                                <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                                    <div className="relative w-full sm:w-56">
                                        <Icon
                                            icon="solar:magnifer-bold-duotone"
                                            className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground"
                                        />
                                        <Input
                                            value={accountSearch}
                                            onChange={(e) => setAccountSearch(e.target.value)}
                                            placeholder={t('settings.mailboxes.search.placeholder')}
                                            className="h-9 pl-9"
                                        />
                                    </div>
                                    <IconButton
                                        type="button"
                                        variant="contained"
                                        color="primary"
                                        size="sm"
                                        className="gap-1"
                                        onClick={() =>
                                            onOpenDialog({
                                                type: 'account',
                                                mode: 'create',
                                                serverId: selectedServer.id,
                                            })
                                        }
                                        icon="material-symbols:add"
                                    />
                                </div>
                            </div>

                            <div className="min-h-0 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]">
                                {serverAccounts.length > 0 ? (
                                    <div className="divide-y">
                                        {serverAccounts.map((account) => (
                                            <MailboxAccountRow
                                                key={account.id}
                                                account={account}
                                                onEdit={(item) => onOpenDialog({ type: 'account', mode: 'edit', item })}
                                                onToggleActive={onToggleActive}
                                                onTestConnection={onTestConnection}
                                                onSync={onSync}
                                                onDelete={onDeleteAccount}
                                            />
                                        ))}
                                    </div>
                                ) : (
                                    <div className="flex flex-col items-center justify-center px-6 py-16 text-center">
                                        <Icon icon="solar:mailbox-bold-duotone" className="mb-3 size-10 text-muted-foreground/60" />
                                        <p className="text-sm font-medium">
                                            {accountSearch
                                                ? t('settings.mailboxes.workspace.no_accounts_search')
                                                : t('settings.mailboxes.workspace.no_accounts_server')}
                                        </p>
                                    </div>
                                )}
                            </div>
                        </div>
                    ) : (
                        <div className="flex flex-1 items-center justify-center p-8 text-sm text-muted-foreground">
                            {t('settings.mailboxes.workspace.select_server')}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
