'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { z } from 'zod';
import { useMutation, useQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { formatDateTime } from '@/lib/date-format';
import { cn } from '@/lib/utils';
import {
  createEmailConfigurationMutation,
  deleteEmailConfigurationMutation,
  sendEmailConfigurationTestEmailMutation,
  testEmailConfigurationConnectionMutation,
  updateEmailConfigurationMutation,
} from '../api/mutations';
import { emailConfigurationsQueryOptions } from '../api/queries';
import type { EmailConfigurationPayload, EmailConfigurationSummary } from '../api/types';

const EMPTY_EMAIL_CONFIGURATIONS: EmailConfigurationSummary[] = [];

const emailConfigurationFormSchema = z.object({
  providerType: z.literal('smtp'),
  name: z.string().trim().min(1, 'Configuration name is required.'),
  host: z.string().trim().min(1, 'SMTP host is required.'),
  port: z
    .string()
    .trim()
    .min(1, 'Port is required.')
    .refine((value) => {
      const port = Number(value);
      return Number.isInteger(port) && port > 0 && port <= 65535;
    }, 'Port must be between 1 and 65535.'),
  secure: z.boolean(),
  username: z.string().trim().max(255).optional(),
  password: z.string().trim().max(1000).optional(),
  clearPassword: z.boolean(),
  fromEmail: z.string().trim().email('From email must be valid.'),
  fromName: z.string().trim().max(255).optional(),
  replyToEmail: z
    .string()
    .trim()
    .optional()
    .refine((value) => !value || z.string().email().safeParse(value).success, 'Reply-to email must be valid.'),
  isDefault: z.boolean(),
  isActive: z.boolean(),
});

type EmailConfigurationFormValues = z.infer<typeof emailConfigurationFormSchema>;

function buildDefaultValues(
  configuration?: EmailConfigurationSummary
): EmailConfigurationFormValues {
  return {
    providerType: 'smtp',
    name: configuration?.name ?? '',
    host: configuration?.host ?? '',
    port: String(configuration?.port ?? 587),
    secure: configuration?.secure ?? false,
    username: configuration?.username ?? '',
    password: '',
    clearPassword: false,
    fromEmail: configuration?.fromEmail ?? '',
    fromName: configuration?.fromName ?? '',
    replyToEmail: configuration?.replyToEmail ?? '',
    isDefault: configuration?.isDefault ?? false,
    isActive: configuration?.isActive ?? true,
  };
}

function statusBadgeVariant(status: EmailConfigurationSummary['lastTestStatus']) {
  if (status === 'failed') return 'destructive';
  if (status === 'passed') return 'default';
  return 'secondary';
}

function SummaryMetric({ label, value, hint }: { label: string; value: string; hint: string }) {
  return (
    <div className='rounded-2xl border border-border/70 bg-background/85 p-4 shadow-sm'>
      <div className='text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground'>
        {label}
      </div>
      <div className='mt-2 text-2xl font-semibold text-foreground'>{value}</div>
      <div className='mt-1 text-sm text-muted-foreground'>{hint}</div>
    </div>
  );
}

function SecurityNote({ title, description }: { title: string; description: string }) {
  return (
    <div className='rounded-2xl border border-border/60 bg-background/80 p-4'>
      <div className='flex items-start gap-3'>
        <div className='rounded-full bg-primary/10 p-2 text-primary'>
          <Icons.lock className='h-4 w-4' />
        </div>
        <div className='space-y-1'>
          <div className='font-medium'>{title}</div>
          <div className='text-sm text-muted-foreground'>{description}</div>
        </div>
      </div>
    </div>
  );
}

function ConfigCard({
  configuration,
  onEdit,
  onDelete,
  onTestConnection,
  onSendTest,
  isDeleting,
  isTesting,
  isSending,
}: {
  configuration: EmailConfigurationSummary;
  onEdit: (configuration: EmailConfigurationSummary) => void;
  onDelete: (configuration: EmailConfigurationSummary) => void;
  onTestConnection: (configuration: EmailConfigurationSummary) => void;
  onSendTest: (configuration: EmailConfigurationSummary) => void;
  isDeleting: boolean;
  isTesting: boolean;
  isSending: boolean;
}) {
  return (
    <Card className='overflow-hidden border-border/70 bg-gradient-to-br from-background via-background to-muted/30 shadow-sm'>
      <CardHeader className='gap-4'>
        <div className='flex flex-wrap items-start justify-between gap-3'>
          <div className='space-y-2'>
            <div className='flex flex-wrap items-center gap-2'>
              <CardTitle className='text-xl'>{configuration.name}</CardTitle>
              {configuration.isDefault ? <Badge>Default</Badge> : null}
              <Badge variant={configuration.isActive ? 'outline' : 'secondary'}>
                {configuration.isActive ? 'Active' : 'Inactive'}
              </Badge>
            </div>
            <CardDescription>
              {configuration.host}:{configuration.port} · {configuration.secure ? 'TLS/SSL' : 'STARTTLS / plain'}
            </CardDescription>
          </div>
          <Badge variant={statusBadgeVariant(configuration.lastTestStatus)}>
            {configuration.lastTestStatus === 'not_tested'
              ? 'Not tested'
              : configuration.lastTestStatus === 'passed'
                ? 'SMTP ready'
                : 'Connection failed'}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className='space-y-5'>
        <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-4'>
          <div className='rounded-xl border border-border/60 bg-background/75 p-3'>
            <div className='text-xs uppercase tracking-[0.14em] text-muted-foreground'>From</div>
            <div className='mt-1 text-sm font-medium'>{configuration.fromEmail}</div>
            <div className='text-sm text-muted-foreground'>{configuration.fromName || 'No display name'}</div>
          </div>
          <div className='rounded-xl border border-border/60 bg-background/75 p-3'>
            <div className='text-xs uppercase tracking-[0.14em] text-muted-foreground'>Auth</div>
            <div className='mt-1 text-sm font-medium'>{configuration.username || 'Anonymous / relay'}</div>
            <div className='text-sm text-muted-foreground'>
              Password {configuration.hasPassword ? 'configured' : 'not configured'}
            </div>
          </div>
          <div className='rounded-xl border border-border/60 bg-background/75 p-3'>
            <div className='text-xs uppercase tracking-[0.14em] text-muted-foreground'>Reply-to</div>
            <div className='mt-1 text-sm font-medium'>
              {configuration.replyToEmail || 'Same as from address'}
            </div>
          </div>
          <div className='rounded-xl border border-border/60 bg-background/75 p-3'>
            <div className='text-xs uppercase tracking-[0.14em] text-muted-foreground'>Last verification</div>
            <div className='mt-1 text-sm font-medium'>
              {configuration.lastTestedAt ? formatDateTime(configuration.lastTestedAt) : 'Never tested'}
            </div>
          </div>
        </div>

        {configuration.lastTestError ? (
          <Alert variant='destructive'>
            <Icons.alertCircle className='h-4 w-4' />
            <AlertTitle>Last SMTP error</AlertTitle>
            <AlertDescription>{configuration.lastTestError}</AlertDescription>
          </Alert>
        ) : null}

        <div className='flex flex-wrap gap-2'>
          <Button type='button' variant='outline' onClick={() => onEdit(configuration)}>
            <Icons.settings className='mr-2 h-4 w-4' />
            Edit
          </Button>
          <Button
            type='button'
            variant='outline'
            onClick={() => onTestConnection(configuration)}
            isLoading={isTesting}
          >
            <Icons.check className='mr-2 h-4 w-4' />
            Test connection
          </Button>
          <Button
            type='button'
            onClick={() => onSendTest(configuration)}
            isLoading={isSending}
          >
            <Icons.send className='mr-2 h-4 w-4' />
            Send test email
          </Button>
          <Button
            type='button'
            variant='outline'
            onClick={() => onDelete(configuration)}
            isLoading={isDeleting}
          >
            <Icons.close className='mr-2 h-4 w-4' />
            Delete
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

function QuickVerificationDialog({
  configuration,
  recipientEmail,
  onRecipientEmailChange,
  onOpenChange,
  onSubmit,
  isSending,
}: {
  configuration: EmailConfigurationSummary | null;
  recipientEmail: string;
  onRecipientEmailChange: (value: string) => void;
  onOpenChange: (open: boolean) => void;
  onSubmit: () => void;
  isSending: boolean;
}) {
  return (
    <Dialog open={configuration !== null} onOpenChange={onOpenChange}>
      <DialogContent className='sm:max-w-md'>
        <DialogHeader>
          <DialogTitle>Quick verification</DialogTitle>
          <DialogDescription>
            {configuration
              ? `Send a test email through ${configuration.name} to verify the active SMTP route.`
              : 'Send a test email to verify the active SMTP route.'}
          </DialogDescription>
        </DialogHeader>

        <div className='space-y-4'>
          {configuration ? (
            <div className='rounded-xl border border-border/60 bg-muted/30 p-3 text-sm'>
              <div className='font-medium text-foreground'>{configuration.name}</div>
              <div className='mt-1 text-muted-foreground'>
                {configuration.host}:{configuration.port} via{' '}
                {configuration.secure ? 'TLS/SSL' : 'STARTTLS / plain'}
              </div>
            </div>
          ) : null}

          <div className='space-y-2'>
            <label className='text-sm font-medium' htmlFor='email-test-recipient'>
              Test recipient
            </label>
            <Input
              id='email-test-recipient'
              type='email'
              value={recipientEmail}
              onChange={(event) => onRecipientEmailChange(event.target.value)}
              placeholder='ops@example.com'
            />
          </div>

          <div className='space-y-3 text-sm text-muted-foreground'>
            <div className='flex items-start gap-3'>
              <Icons.check className='mt-0.5 h-4 w-4 text-primary' />
              <span>Connection test updates health state without exposing the stored password.</span>
            </div>
            <div className='flex items-start gap-3'>
              <Icons.lock className='mt-0.5 h-4 w-4 text-primary' />
              <span>Stored passwords can be replaced or cleared, but are never returned from the API.</span>
            </div>
            <div className='flex items-start gap-3'>
              <Icons.settings className='mt-0.5 h-4 w-4 text-primary' />
              <span>Setup wizard and notification runtime use the same organization-level SMTP source.</span>
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)} disabled={isSending}>
            Cancel
          </Button>
          <Button type='button' onClick={onSubmit} isLoading={isSending} disabled={!recipientEmail.trim()}>
            <Icons.send className={cn('mr-2 h-4 w-4', isSending && 'hidden')} />
            Send test email
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export function EmailConfigurationPage() {
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editingConfiguration, setEditingConfiguration] = useState<EmailConfigurationSummary | null>(null);
  const [quickVerificationConfiguration, setQuickVerificationConfiguration] =
    useState<EmailConfigurationSummary | null>(null);
  const [quickVerificationRecipientEmail, setQuickVerificationRecipientEmail] = useState('');

  const emailConfigurationsQuery = useQuery(emailConfigurationsQueryOptions());
  const createMutation = useMutation(createEmailConfigurationMutation);
  const updateMutation = useMutation(updateEmailConfigurationMutation);
  const deleteMutation = useMutation(deleteEmailConfigurationMutation);
  const testConnectionMutation = useMutation(testEmailConfigurationConnectionMutation);
  const sendTestEmailMutation = useMutation(sendEmailConfigurationTestEmailMutation);

  const configurations = emailConfigurationsQuery.data ?? EMPTY_EMAIL_CONFIGURATIONS;
  const summary = useMemo(() => {
    const activeCount = configurations.filter((item) => item.isActive).length;
    const passingCount = configurations.filter((item) => item.lastTestStatus === 'passed').length;
    const defaultConfig = configurations.find((item) => item.isDefault) ?? null;

    return {
      total: configurations.length,
      activeCount,
      passingCount,
      defaultName: defaultConfig?.name ?? 'Not selected',
    };
  }, [configurations]);

  const defaultValues = useMemo(
    () => buildDefaultValues(editingConfiguration ?? undefined),
    [editingConfiguration]
  );

  const { FormTextField, FormSwitchField } = useFormFields<EmailConfigurationFormValues>();
  const form = useAppForm({
    defaultValues,
    validators: {
      onSubmit: emailConfigurationFormSchema,
    },
    onSubmit: async ({ value }) => {
      const payload: EmailConfigurationPayload = {
        providerType: 'smtp',
        name: value.name.trim(),
        host: value.host.trim(),
        port: Number(value.port),
        secure: value.secure,
        username: value.username?.trim() || null,
        password: value.password?.trim() || undefined,
        clearPassword: value.clearPassword,
        fromEmail: value.fromEmail.trim().toLowerCase(),
        fromName: value.fromName?.trim() || null,
        replyToEmail: value.replyToEmail?.trim() || null,
        isDefault: value.isDefault,
        isActive: value.isActive,
      };

      if (editingConfiguration) {
        await updateMutation.mutateAsync({
          id: editingConfiguration.id,
          payload,
        });
        toast.success('Email configuration updated.');
      } else {
        await createMutation.mutateAsync(payload);
        toast.success('Email configuration created.');
      }

      setSheetOpen(false);
      setEditingConfiguration(null);
    },
  });

  useEffect(() => {
    if (sheetOpen) {
      form.reset(defaultValues);
    }
  }, [defaultValues, form, sheetOpen]);

  async function handleDelete(configuration: EmailConfigurationSummary) {
    try {
      await deleteMutation.mutateAsync(configuration.id);
      toast.success(`Removed ${configuration.name}.`);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Unable to delete email configuration.');
    }
  }

  async function handleTestConnection(configuration: EmailConfigurationSummary) {
    try {
      const result = await testConnectionMutation.mutateAsync(configuration.id);
      if (!result.ok) {
        toast.error(result.detail ?? 'SMTP connection failed.');
        return;
      }
      toast.success(`SMTP connection succeeded for ${configuration.name}.`);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Unable to test SMTP connection.');
    }
  }

  async function handleSendTest() {
    if (!quickVerificationConfiguration) {
      return;
    }

    const normalizedRecipientEmail = quickVerificationRecipientEmail.trim().toLowerCase();

    try {
      const result = await sendTestEmailMutation.mutateAsync({
        id: quickVerificationConfiguration.id,
        payload: {
          recipientEmail: normalizedRecipientEmail,
        },
      });

      if (result.rejectedRecipients.length > 0) {
        toast.error(`SMTP rejected: ${result.rejectedRecipients.join(', ')}`);
        return;
      }

      toast.success(`Test email queued to ${normalizedRecipientEmail}.`);
      setQuickVerificationConfiguration(null);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Unable to send test email.');
    }
  }

  const saving = createMutation.isPending || updateMutation.isPending;

  return (
    <div className='space-y-6'>
      <section className='overflow-hidden rounded-[28px] border border-border/60 bg-[linear-gradient(135deg,rgba(240,246,255,0.9),rgba(255,255,255,0.96),rgba(243,247,252,0.92))] shadow-sm'>
        <div className='grid gap-6 px-6 py-6 lg:grid-cols-[1.4fr_0.9fr] lg:px-8'>
          <div className='space-y-5'>
            <div className='inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 py-1 text-xs font-medium tracking-[0.16em] text-primary uppercase'>
              <Icons.send className='h-3.5 w-3.5' />
              Email delivery center
            </div>
            <div className='space-y-3'>
              <h2 className='max-w-3xl text-3xl font-semibold tracking-tight text-foreground'>
                Manage SMTP delivery in one calm, auditable place.
              </h2>
              <p className='max-w-2xl text-sm leading-6 text-muted-foreground'>
                Configure secure outbound email for approvals, password recovery, invitations, and setup warnings.
                Secrets stay encrypted at rest and the UI only exposes safe operational state.
              </p>
            </div>
            <div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-4'>
              <SummaryMetric
                label='Configurations'
                value={String(summary.total)}
                hint='Stored SMTP profiles'
              />
              <SummaryMetric
                label='Active'
                value={String(summary.activeCount)}
                hint='Eligible for delivery'
              />
              <SummaryMetric
                label='Passing'
                value={String(summary.passingCount)}
                hint='Last SMTP test passed'
              />
              <SummaryMetric
                label='Default route'
                value={summary.defaultName}
                hint='Used by notification runtime'
              />
            </div>
          </div>

          <Card className='border-border/60 bg-background/80 shadow-none'>
            <CardHeader>
              <CardTitle>Operator actions</CardTitle>
              <CardDescription>
                Create and maintain SMTP routes for setup, notifications, and approvals.
              </CardDescription>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='space-y-3 text-sm text-muted-foreground'>
                <div className='flex items-start gap-3'>
                  <Icons.check className='mt-0.5 h-4 w-4 text-primary' />
                  <span>Add a route, then use each row&apos;s quick verification modal to send a test email.</span>
                </div>
                <div className='flex items-start gap-3'>
                  <Icons.lock className='mt-0.5 h-4 w-4 text-primary' />
                  <span>Stored passwords can be replaced or cleared, but are never returned from the API.</span>
                </div>
                <div className='flex items-start gap-3'>
                  <Icons.settings className='mt-0.5 h-4 w-4 text-primary' />
                  <span>Setup wizard and notification runtime read the same organization-level SMTP source.</span>
                </div>
              </div>
              <div className='flex flex-wrap gap-2'>
                <Button
                  type='button'
                  onClick={() => {
                    setEditingConfiguration(null);
                    setSheetOpen(true);
                  }}
                >
                  <Icons.check className='mr-2 h-4 w-4' />
                  Add configuration
                </Button>
                <Button asChild type='button' variant='outline'>
                  <Link href='/dashboard/administration/setup'>Open setup wizard</Link>
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </section>

      <div className='grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]'>
        <div className='space-y-4'>
          {emailConfigurationsQuery.isLoading ? (
            <Card>
              <CardContent className='flex items-center gap-3 p-6 text-sm text-muted-foreground'>
                <Icons.spinner className='h-4 w-4 animate-spin' />
                Loading email configurations...
              </CardContent>
            </Card>
          ) : null}

          {emailConfigurationsQuery.isError ? (
            <Alert variant='destructive'>
              <Icons.alertCircle className='h-4 w-4' />
              <AlertTitle>Unable to load SMTP profiles</AlertTitle>
              <AlertDescription>
                {emailConfigurationsQuery.error instanceof Error
                  ? emailConfigurationsQuery.error.message
                  : 'Unknown email configuration error.'}
              </AlertDescription>
            </Alert>
          ) : null}

          {!emailConfigurationsQuery.isLoading && configurations.length === 0 ? (
            <Card className='border-dashed'>
              <CardContent className='flex flex-col items-center gap-3 px-6 py-12 text-center'>
                <div className='rounded-full bg-primary/10 p-3 text-primary'>
                  <Icons.send className='h-6 w-6' />
                </div>
                <div className='space-y-2'>
                  <div className='text-lg font-semibold'>No SMTP configuration yet</div>
                  <div className='max-w-xl text-sm text-muted-foreground'>
                    Add a profile to enable outbound email for system notifications, approvals, and future workflow messages.
                  </div>
                </div>
                <Button
                  type='button'
                  onClick={() => {
                    setEditingConfiguration(null);
                    setSheetOpen(true);
                  }}
                >
                  <Icons.check className='mr-2 h-4 w-4' />
                  Create first configuration
                </Button>
              </CardContent>
            </Card>
          ) : null}

          {configurations.map((configuration) => (
            <ConfigCard
              key={configuration.id}
              configuration={configuration}
              onEdit={(item) => {
                setEditingConfiguration(item);
                setSheetOpen(true);
              }}
              onDelete={handleDelete}
              onTestConnection={handleTestConnection}
              onSendTest={(item) => {
                setQuickVerificationConfiguration(item);
              }}
              isDeleting={deleteMutation.isPending && deleteMutation.variables === configuration.id}
              isTesting={
                testConnectionMutation.isPending &&
                testConnectionMutation.variables === configuration.id
              }
              isSending={
                sendTestEmailMutation.isPending &&
                sendTestEmailMutation.variables?.id === configuration.id
              }
            />
          ))}
        </div>

        <aside className='space-y-4'>
          <Card className='border-border/70 bg-muted/20'>
            <CardHeader>
              <CardTitle>Operator notes</CardTitle>
              <CardDescription>
                A calm checklist for setup and post-go-live operations.
              </CardDescription>
            </CardHeader>
            <CardContent className='space-y-3'>
              <SecurityNote
                title='Encrypt before save'
                description='Saving a password requires EMAIL_CONFIG_ENCRYPTION_KEY on the server.'
              />
              <SecurityNote
                title='Choose one default route'
                description='The notification runtime will prefer the organization default SMTP profile.'
              />
              <SecurityNote
                title='Verify after every credential change'
                description='Run connection test and test email again whenever host, username, or password changes.'
              />
            </CardContent>
          </Card>
        </aside>
      </div>

      <Sheet
        open={sheetOpen}
        onOpenChange={(open) => {
          setSheetOpen(open);
          if (!open) {
            setEditingConfiguration(null);
          }
        }}
      >
        <SheetContent side='right' className='w-full overflow-y-auto sm:max-w-2xl'>
          <SheetHeader>
            <SheetTitle>{editingConfiguration ? 'Edit SMTP configuration' : 'Add SMTP configuration'}</SheetTitle>
            <SheetDescription>
              Keep the profile readable for operators. Passwords can be updated, but never viewed again.
            </SheetDescription>
          </SheetHeader>

          <div className='mt-6'>
            <form.AppForm>
              <form.Form className='space-y-4' id='email-configuration-form'>
                <div className='grid gap-4 md:grid-cols-2'>
                  <FormTextField
                    name='name'
                    label='Configuration name'
                    placeholder='Primary corporate SMTP'
                    required
                  />
                  <FormTextField
                    name='host'
                    label='SMTP host'
                    placeholder='smtp.example.com'
                    required
                  />
                  <FormTextField
                    name='port'
                    label='Port'
                    placeholder='587'
                    required
                  />
                  <FormTextField
                    name='username'
                    label='Username'
                    placeholder='mailer@example.com'
                  />
                  <FormTextField
                    name='password'
                    label={editingConfiguration?.hasPassword ? 'Replace password' : 'Password'}
                    type='password'
                    placeholder={editingConfiguration?.hasPassword ? 'Leave blank to keep existing password' : 'SMTP password'}
                  />
                  <FormTextField
                    name='fromEmail'
                    label='From email'
                    type='email'
                    placeholder='noreply@example.com'
                    required
                  />
                  <FormTextField
                    name='fromName'
                    label='From name'
                    placeholder='ALLA OS'
                  />
                  <FormTextField
                    name='replyToEmail'
                    label='Reply-to email'
                    type='email'
                    placeholder='support@example.com'
                  />
                </div>

                <div className='grid gap-3 rounded-2xl border border-border/70 bg-muted/25 p-4'>
                  <FormSwitchField
                    name='secure'
                    label='Use secure SMTP transport'
                    description='Enable this when the provider expects implicit TLS, usually on port 465.'
                  />
                  <FormSwitchField
                    name='isDefault'
                    label='Make this the default delivery route'
                    description='The default profile is used by email notifications when no override is selected.'
                  />
                  <FormSwitchField
                    name='isActive'
                    label='Allow this profile for runtime delivery'
                    description='Inactive profiles stay visible for audit and editing, but are skipped for sending.'
                  />
                  {editingConfiguration?.hasPassword ? (
                    <FormSwitchField
                      name='clearPassword'
                      label='Clear stored password on save'
                      description='Use this only when the SMTP server no longer requires the stored credential.'
                    />
                  ) : null}
                </div>
              </form.Form>
            </form.AppForm>
          </div>

          <SheetFooter className='mt-6'>
            <Button
              type='button'
              variant='outline'
              onClick={() => {
                setSheetOpen(false);
                setEditingConfiguration(null);
              }}
              disabled={saving}
            >
              Cancel
            </Button>
            <Button type='submit' form='email-configuration-form' isLoading={saving}>
              <Icons.check className={cn('mr-2 h-4 w-4', saving && 'hidden')} />
              {editingConfiguration ? 'Save changes' : 'Create configuration'}
            </Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>

      <QuickVerificationDialog
        configuration={quickVerificationConfiguration}
        recipientEmail={quickVerificationRecipientEmail}
        onRecipientEmailChange={setQuickVerificationRecipientEmail}
        onOpenChange={(open) => {
          if (!open) {
            setQuickVerificationConfiguration(null);
          }
        }}
        onSubmit={handleSendTest}
        isSending={sendTestEmailMutation.isPending}
      />
    </div>
  );
}
