'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Mail, Plus, Trash2, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface Account {
  id: string;
  provider: 'google' | 'outlook' | 'custom';
  emailAddress: string;
  smtpHost: string;
  smtpPort: number;
  imapHost: string;
  imapPort: number;
  username: string;
  isActive: boolean;
  lastSyncAt: string | null;
}

const PROVIDER_DEFAULTS: Record<
  string,
  { smtpHost: string; smtpPort: number; imapHost: string; imapPort: number }
> = {
  google: { smtpHost: 'smtp.gmail.com', smtpPort: 587, imapHost: 'imap.gmail.com', imapPort: 993 },
  outlook: {
    smtpHost: 'smtp.office365.com',
    smtpPort: 587,
    imapHost: 'outlook.office365.com',
    imapPort: 993,
  },
  custom: { smtpHost: '', smtpPort: 587, imapHost: '', imapPort: 993 },
};

export function EmailAccountsList() {
  const qc = useQueryClient();
  const [sheetOpen, setSheetOpen] = useState(false);
  const [form, setForm] = useState({
    provider: 'google' as 'google' | 'outlook' | 'custom',
    emailAddress: '',
    smtpHost: PROVIDER_DEFAULTS.google!.smtpHost,
    smtpPort: PROVIDER_DEFAULTS.google!.smtpPort,
    imapHost: PROVIDER_DEFAULTS.google!.imapHost,
    imapPort: PROVIDER_DEFAULTS.google!.imapPort,
    username: '',
    password: '',
  });

  const { data: accounts = [], isLoading } = useQuery<Account[]>({
    queryKey: ['email', 'accounts'],
    queryFn: () => apiFetch<{ data: Account[] }>('/api/v1/email/accounts').then((r) => r.data),
  });

  const createMutation = useMutation({
    mutationFn: () => apiFetch('/api/v1/email/accounts', { method: 'POST', body: form }),
    onSuccess: () => {
      toast.success('Account connected');
      setSheetOpen(false);
      qc.invalidateQueries({ queryKey: ['email', 'accounts'] });
    },
    onError: (err) => toastError(err),
  });

  const toggleMutation = useMutation({
    mutationFn: ({ id, isActive }: { id: string; isActive: boolean }) =>
      apiFetch(`/api/v1/email/accounts/${id}`, {
        method: 'PATCH',
        body: { isActive },
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['email', 'accounts'] }),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/email/accounts/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      toast.success('Account removed');
      qc.invalidateQueries({ queryKey: ['email', 'accounts'] });
    },
  });

  const syncMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/email/accounts/${id}/sync`, { method: 'POST' }),
    onSuccess: () => {
      toast.success('Sync started');
      qc.invalidateQueries({ queryKey: ['email', 'accounts'] });
    },
  });

  function setProvider(provider: 'google' | 'outlook' | 'custom') {
    const defaults = PROVIDER_DEFAULTS[provider]!;
    setForm({ ...form, provider, ...defaults });
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-lg font-semibold">Connected Accounts</h2>
          <p className="text-sm text-muted-foreground">
            IMAP/SMTP accounts used for sending and receiving client emails.
          </p>
        </div>
        <Button onClick={() => setSheetOpen(true)}>
          <Plus className="h-4 w-4 mr-1.5" aria-hidden />
          Add account
        </Button>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : accounts.length === 0 ? (
        <div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
          <Mail className="mx-auto h-6 w-6 mb-2" aria-hidden />
          <p className="text-sm">No email accounts connected.</p>
        </div>
      ) : (
        <div className="rounded-lg border divide-y">
          {accounts.map((a) => (
            <div key={a.id} className="flex items-center gap-3 p-3">
              <Mail className="h-5 w-5 text-muted-foreground" aria-hidden />
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium truncate">{a.emailAddress}</div>
                <div className="text-xs text-muted-foreground">
                  {a.provider} · {a.imapHost}
                  {a.lastSyncAt && ` · last sync ${new Date(a.lastSyncAt).toLocaleString()}`}
                </div>
              </div>
              <Switch
                checked={a.isActive}
                onCheckedChange={(v) => toggleMutation.mutate({ id: a.id, isActive: v })}
              />
              <Button
                variant="ghost"
                size="icon"
                onClick={() => syncMutation.mutate(a.id)}
                disabled={syncMutation.isPending}
                title="Sync now"
              >
                <RefreshCw className="h-4 w-4" aria-hidden />
              </Button>
              <ConfirmationDialog
                trigger={
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-destructive"
                    aria-label="Remove account"
                  >
                    <Trash2 className="h-4 w-4" aria-hidden />
                  </Button>
                }
                title="Remove account"
                description={`Disconnect ${a.emailAddress}?`}
                confirmLabel="Remove"
                onConfirm={() => deleteMutation.mutate(a.id)}
              />
            </div>
          ))}
        </div>
      )}

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent className="overflow-y-auto">
          <SheetHeader>
            <SheetTitle>Connect email account</SheetTitle>
          </SheetHeader>
          <div className="space-y-3 py-4">
            <div className="space-y-1">
              <Label>Provider</Label>
              <Select
                value={form.provider}
                onValueChange={(v) => setProvider(v as 'google' | 'outlook' | 'custom')}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="google">Google</SelectItem>
                  <SelectItem value="outlook">Outlook / Office 365</SelectItem>
                  <SelectItem value="custom">Custom IMAP/SMTP</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label>Email address</Label>
              <Input
                type="email"
                value={form.emailAddress}
                onChange={(e) =>
                  setForm({ ...form, emailAddress: e.target.value, username: e.target.value })
                }
              />
            </div>
            <div className="space-y-1">
              <Label>Username</Label>
              <Input
                value={form.username}
                onChange={(e) => setForm({ ...form, username: e.target.value })}
              />
            </div>
            <div className="space-y-1">
              <Label>Password / App password</Label>
              <Input
                type="password"
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
              />
            </div>
            <div className="grid grid-cols-2 gap-2">
              <div className="space-y-1">
                <Label>SMTP host</Label>
                <Input
                  value={form.smtpHost}
                  onChange={(e) => setForm({ ...form, smtpHost: e.target.value })}
                />
              </div>
              <div className="space-y-1">
                <Label>SMTP port</Label>
                <Input
                  type="number"
                  value={form.smtpPort}
                  onChange={(e) => setForm({ ...form, smtpPort: Number(e.target.value) })}
                />
              </div>
              <div className="space-y-1">
                <Label>IMAP host</Label>
                <Input
                  value={form.imapHost}
                  onChange={(e) => setForm({ ...form, imapHost: e.target.value })}
                />
              </div>
              <div className="space-y-1">
                <Label>IMAP port</Label>
                <Input
                  type="number"
                  value={form.imapPort}
                  onChange={(e) => setForm({ ...form, imapPort: Number(e.target.value) })}
                />
              </div>
            </div>
          </div>
          <SheetFooter>
            <Button variant="ghost" onClick={() => setSheetOpen(false)}>
              Cancel
            </Button>
            <Button onClick={() => createMutation.mutate()} disabled={createMutation.isPending}>
              {createMutation.isPending ? 'Connecting…' : 'Connect'}
            </Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>
    </div>
  );
}
