'use client';

import type React from 'react';

import {
  EmptyState,
  Page,
  PageHeader,
  PaginationFooter,
  SearchBar,
} from '@/components/entity-list';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { ResizableSheetContent } from '@/components/ui/resizable-sheet-content';
import {
  Sheet,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import { Switch } from '@/components/ui/switch';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { usePagination } from '@/hooks/use-pagination';
import { formatDate } from '@/lib/format-date';
import { useApp } from '@hed-hog/next-app-provider';
import { Mail, Pencil, Send, Trash2 } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

type ProviderType = 'SMTP' | 'GMAIL' | 'SES';

type MailProfile = {
  id: number;
  slug: string;
  name: string;
  provider: ProviderType;
  from_name?: string | null;
  from_email: string;
  reply_to_name?: string | null;
  reply_to_email?: string | null;
  smtp_host?: string | null;
  smtp_port?: number | null;
  smtp_secure?: boolean;
  smtp_username?: string | null;
  smtp_password?: string | null;
  gmail_client_id?: string | null;
  gmail_client_secret?: string | null;
  gmail_refresh_token?: string | null;
  ses_access_key_id?: string | null;
  ses_secret_access_key?: string | null;
  ses_region?: string | null;
  created_at: string;
  updated_at: string;
};

type MailProfileForm = {
  slug: string;
  name: string;
  provider: ProviderType;
  from_name: string;
  from_email: string;
  reply_to_name: string;
  reply_to_email: string;
  smtp_host: string;
  smtp_port: string;
  smtp_secure: boolean;
  smtp_username: string;
  smtp_password: string;
  gmail_client_id: string;
  gmail_client_secret: string;
  gmail_refresh_token: string;
  ses_access_key_id: string;
  ses_secret_access_key: string;
  ses_region: string;
};

const defaultFormData = (): MailProfileForm => ({
  slug: '',
  name: '',
  provider: 'SMTP',
  from_name: '',
  from_email: '',
  reply_to_name: '',
  reply_to_email: '',
  smtp_host: '',
  smtp_port: '587',
  smtp_secure: true,
  smtp_username: '',
  smtp_password: '',
  gmail_client_id: '',
  gmail_client_secret: '',
  gmail_refresh_token: '',
  ses_access_key_id: '',
  ses_secret_access_key: '',
  ses_region: '',
});

export default function MailProfilesPage() {
  const t = useTranslations('core.MailProfilePage');
  const { request, currentLocaleCode, getSettingValue } = useApp();
  const {
    items,
    refetch,
    page,
    setPage,
    pageSize,
    setPageSize,
    totalItems,
    search,
    setSearch,
  } = usePagination({ url: '/mail-profile' });

  const [profiles, setProfiles] = useState<MailProfile[]>([]);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [profileToDelete, setProfileToDelete] = useState<number | null>(null);
  const [selectedProfile, setSelectedProfile] = useState<MailProfile | null>(
    null
  );
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState<MailProfileForm>(defaultFormData());
  const [isTesting, setIsTesting] = useState(false);
  const [testedSignature, setTestedSignature] = useState<string | null>(null);

  useEffect(() => {
    setProfiles(Array.isArray(items) ? (items as MailProfile[]) : []);
  }, [items]);

  const handleCreate = () => {
    setEditMode(false);
    setSelectedProfile(null);
    setFormData(defaultFormData());
    setTestedSignature(null);
    setIsDialogOpen(true);
  };

  const handleEdit = async (profile: MailProfile) => {
    setEditMode(true);
    setSelectedProfile(profile);
    setTestedSignature(null);
    setIsDialogOpen(true);

    try {
      const { data } = await request<MailProfile>({
        url: `/mail-profile/${profile.id}`,
        method: 'GET',
      });

      setFormData({
        slug: data.slug ?? '',
        name: data.name ?? '',
        provider: data.provider ?? 'SMTP',
        from_name: data.from_name ?? '',
        from_email: data.from_email ?? '',
        reply_to_name: data.reply_to_name ?? '',
        reply_to_email: data.reply_to_email ?? '',
        smtp_host: data.smtp_host ?? '',
        smtp_port: data.smtp_port ? String(data.smtp_port) : '587',
        smtp_secure: Boolean(data.smtp_secure),
        smtp_username: data.smtp_username ?? '',
        smtp_password: data.smtp_password ?? '',
        gmail_client_id: data.gmail_client_id ?? '',
        gmail_client_secret: data.gmail_client_secret ?? '',
        gmail_refresh_token: data.gmail_refresh_token ?? '',
        ses_access_key_id: data.ses_access_key_id ?? '',
        ses_secret_access_key: data.ses_secret_access_key ?? '',
        ses_region: data.ses_region ?? '',
      });
    } catch (error) {
      console.error('Error loading mail profile:', error);
      toast.error(t('loadError'));
    }
  };

  const handleDelete = (id: number) => {
    setProfileToDelete(id);
    setIsDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (profileToDelete === null) {
      return;
    }

    try {
      await request({
        url: '/mail-profile',
        method: 'DELETE',
        data: { ids: [profileToDelete] },
      });
      toast.success(t('deleteSuccess'));
      setProfileToDelete(null);
      setIsDeleteDialogOpen(false);
      refetch();
    } catch (error) {
      console.error('Error deleting mail profile:', error);
      toast.error(t('deleteError'));
    }
  };

  const updateFormField = <K extends keyof MailProfileForm>(
    field: K,
    value: MailProfileForm[K]
  ) => {
    setFormData((current) => ({
      ...current,
      [field]: value,
    }));
  };

  const handleProviderChange = (provider: ProviderType) => {
    setFormData((current) => ({
      ...current,
      provider,
    }));
  };

  const createPayload = () => ({
    slug: formData.slug,
    name: formData.name,
    provider: formData.provider,
    from_name: formData.from_name || undefined,
    from_email: formData.from_email,
    reply_to_name: formData.reply_to_name || undefined,
    reply_to_email: formData.reply_to_email || undefined,
    smtp_host: formData.smtp_host || undefined,
    smtp_port: formData.smtp_port ? Number(formData.smtp_port) : undefined,
    smtp_secure: formData.smtp_secure,
    smtp_username: formData.smtp_username || undefined,
    smtp_password: formData.smtp_password || undefined,
    gmail_client_id: formData.gmail_client_id || undefined,
    gmail_client_secret: formData.gmail_client_secret || undefined,
    gmail_refresh_token: formData.gmail_refresh_token || undefined,
    ses_access_key_id: formData.ses_access_key_id || undefined,
    ses_secret_access_key: formData.ses_secret_access_key || undefined,
    ses_region: formData.ses_region || undefined,
  });

  const currentSignature = JSON.stringify(createPayload());

  const canSubmitProfile = testedSignature === currentSignature;

  const handleTest = async () => {
    const payload = createPayload();

    try {
      setIsTesting(true);
      const { data } = await request<{ success: boolean; destination: string }>({
        url: '/mail-profile/test',
        method: 'POST',
        data: payload,
      });

      setTestedSignature(JSON.stringify(payload));
      toast.success(
        t('testSuccess', {
          email: data.destination || payload.from_email,
        })
      );
    } catch (error) {
      console.error('Error testing mail profile:', error);
      setTestedSignature(null);
      toast.error(t('testError'));
    } finally {
      setIsTesting(false);
    }
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();

    const payload = createPayload();

    try {
      if (editMode && selectedProfile) {
        await request({
          url: `/mail-profile/${selectedProfile.id}`,
          method: 'PATCH',
          data: payload,
        });
        toast.success(t('updateSuccess'));
      } else {
        await request({
          url: '/mail-profile',
          method: 'POST',
          data: payload,
        });
        toast.success(t('createSuccess'));
      }

      setIsDialogOpen(false);
      setTestedSignature(null);
      refetch();
    } catch (error) {
      console.error('Error saving mail profile:', error);
      toast.error(editMode ? t('updateError') : t('createError'));
    }
  };

  const renderSender = (profile: MailProfile) => {
    if (profile.from_name) {
      return `${profile.from_name} <${profile.from_email}>`;
    }

    return profile.from_email;
  };

  const renderReplyTo = (profile: MailProfile) => {
    if (!profile.reply_to_email) {
      return t('notConfigured');
    }

    if (profile.reply_to_name) {
      return `${profile.reply_to_name} <${profile.reply_to_email}>`;
    }

    return profile.reply_to_email;
  };

  return (
    <Page>
      <PageHeader
        breadcrumbs={[
          { label: t('breadcrumbHome'), href: '/' },
          { label: t('breadcrumbTitle') },
        ]}
        actions={[
          {
            label: t('newProfile'),
            onClick: handleCreate,
            variant: 'default' as const,
          },
        ]}
        title={t('title')}
        description={t('description')}
      />

      <SearchBar
        searchQuery={search}
        onSearchChange={(value) => {
          setSearch(value);
          setPage(1);
        }}
        onSearch={() => setPage(1)}
        placeholder={t('searchPlaceholder')}
      />

      {profiles.length === 0 ? (
        <EmptyState
          icon={<Send className="h-12 w-12" />}
          title={t('noProfilesFound')}
          description={t('noProfilesHint')}
          actionLabel={t('newProfile')}
          onAction={handleCreate}
        />
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t('tableName')}</TableHead>
                <TableHead>{t('tableSlug')}</TableHead>
                <TableHead>{t('tableProvider')}</TableHead>
                <TableHead>{t('tableSender')}</TableHead>
                <TableHead>{t('tableReplyTo')}</TableHead>
                <TableHead>{t('tableUpdated')}</TableHead>
                <TableHead className="text-right">
                  {t('tableActions')}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {profiles.map((profile) => (
                <TableRow
                  key={profile.id}
                  className="cursor-pointer"
                  onDoubleClick={() => handleEdit(profile)}
                >
                  <TableCell className="font-medium">{profile.name}</TableCell>
                  <TableCell className="font-mono text-sm">
                    {profile.slug}
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary">{profile.provider}</Badge>
                  </TableCell>
                  <TableCell>{renderSender(profile)}</TableCell>
                  <TableCell>{renderReplyTo(profile)}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {formatDate(
                      profile.updated_at,
                      getSettingValue,
                      currentLocaleCode
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={(event) => {
                          event.stopPropagation();
                          handleEdit(profile);
                        }}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={(event) => {
                          event.stopPropagation();
                          handleDelete(profile.id);
                        }}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <PaginationFooter
        currentPage={page}
        pageSize={pageSize}
        totalItems={totalItems}
        onPageChange={setPage}
        onPageSizeChange={(newSize) => {
          setPageSize(newSize);
          setPage(1);
        }}
      />

      <Sheet open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <ResizableSheetContent sheetId="mail-profile-editor" defaultWidth={896}>
          <SheetHeader>
            <SheetTitle>
              {editMode ? t('editProfile') : t('newProfileTitle')}
            </SheetTitle>
            <SheetDescription>
              {editMode
                ? t('editProfileDescription')
                : t('newProfileDescription')}
            </SheetDescription>
          </SheetHeader>

          <form onSubmit={handleSubmit} className="space-y-6 px-3 pb-8 sm:px-4">
            <div className="grid gap-6 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="name">{t('nameLabel')}</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(event) =>
                    updateFormField('name', event.target.value)
                  }
                  placeholder={t('namePlaceholder')}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="slug">{t('slugLabel')}</Label>
                <Input
                  id="slug"
                  value={formData.slug}
                  onChange={(event) =>
                    updateFormField('slug', event.target.value)
                  }
                  placeholder={t('slugPlaceholder')}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="provider">{t('providerLabel')}</Label>
                <Select
                  value={formData.provider}
                  onValueChange={handleProviderChange}
                >
                  <SelectTrigger className="w-full" id="provider">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="SMTP">{t('providerSMTP')}</SelectItem>
                    <SelectItem value="GMAIL">{t('providerGmail')}</SelectItem>
                    <SelectItem value="SES">{t('providerSES')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="from-email">{t('fromEmailLabel')}</Label>
                <Input
                  id="from-email"
                  type="email"
                  value={formData.from_email}
                  onChange={(event) =>
                    updateFormField('from_email', event.target.value)
                  }
                  placeholder={t('fromEmailPlaceholder')}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="from-name">{t('fromNameLabel')}</Label>
                <Input
                  id="from-name"
                  value={formData.from_name}
                  onChange={(event) =>
                    updateFormField('from_name', event.target.value)
                  }
                  placeholder={t('fromNamePlaceholder')}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="reply-to-email">{t('replyToEmailLabel')}</Label>
                <Input
                  id="reply-to-email"
                  type="email"
                  value={formData.reply_to_email}
                  onChange={(event) =>
                    updateFormField('reply_to_email', event.target.value)
                  }
                  placeholder={t('replyToEmailPlaceholder')}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="reply-to-name">{t('replyToNameLabel')}</Label>
                <Input
                  id="reply-to-name"
                  value={formData.reply_to_name}
                  onChange={(event) =>
                    updateFormField('reply_to_name', event.target.value)
                  }
                  placeholder={t('replyToNamePlaceholder')}
                />
              </div>
            </div>

            {formData.provider === 'SMTP' ? (
              <div className="space-y-4 rounded-lg border p-4">
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4" />
                  <h3 className="text-sm font-semibold">
                    {t('smtpSectionTitle')}
                  </h3>
                </div>
                <div className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="smtp-host">{t('smtpHostLabel')}</Label>
                    <Input
                      id="smtp-host"
                      value={formData.smtp_host}
                      onChange={(event) =>
                        updateFormField('smtp_host', event.target.value)
                      }
                      placeholder={t('smtpHostPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-port">{t('smtpPortLabel')}</Label>
                    <Input
                      id="smtp-port"
                      type="number"
                      min="1"
                      value={formData.smtp_port}
                      onChange={(event) =>
                        updateFormField('smtp_port', event.target.value)
                      }
                      placeholder={t('smtpPortPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-username">
                      {t('smtpUsernameLabel')}
                    </Label>
                    <Input
                      id="smtp-username"
                      value={formData.smtp_username}
                      onChange={(event) =>
                        updateFormField('smtp_username', event.target.value)
                      }
                      placeholder={t('smtpUsernamePlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-password">
                      {t('smtpPasswordLabel')}
                    </Label>
                    <Input
                      id="smtp-password"
                      type="password"
                      value={formData.smtp_password}
                      onChange={(event) =>
                        updateFormField('smtp_password', event.target.value)
                      }
                      placeholder={t('smtpPasswordPlaceholder')}
                      required
                    />
                  </div>
                </div>
                <div className="flex items-center justify-between rounded-md border px-4 py-3">
                  <div className="space-y-1">
                    <p className="text-sm font-medium">
                      {t('smtpSecureLabel')}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {t('smtpSecureHelp')}
                    </p>
                  </div>
                  <Switch
                    checked={formData.smtp_secure}
                    onCheckedChange={(checked) =>
                      updateFormField('smtp_secure', checked)
                    }
                  />
                </div>
              </div>
            ) : null}

            {formData.provider === 'GMAIL' ? (
              <div className="space-y-4 rounded-lg border p-4">
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4" />
                  <h3 className="text-sm font-semibold">
                    {t('gmailSectionTitle')}
                  </h3>
                </div>
                <div className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="gmail-client-id">
                      {t('gmailClientIdLabel')}
                    </Label>
                    <Input
                      id="gmail-client-id"
                      value={formData.gmail_client_id}
                      onChange={(event) =>
                        updateFormField('gmail_client_id', event.target.value)
                      }
                      placeholder={t('gmailClientIdPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="gmail-client-secret">
                      {t('gmailClientSecretLabel')}
                    </Label>
                    <Input
                      id="gmail-client-secret"
                      type="password"
                      value={formData.gmail_client_secret}
                      onChange={(event) =>
                        updateFormField(
                          'gmail_client_secret',
                          event.target.value
                        )
                      }
                      placeholder={t('gmailClientSecretPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="gmail-refresh-token">
                      {t('gmailRefreshTokenLabel')}
                    </Label>
                    <Input
                      id="gmail-refresh-token"
                      type="password"
                      value={formData.gmail_refresh_token}
                      onChange={(event) =>
                        updateFormField(
                          'gmail_refresh_token',
                          event.target.value
                        )
                      }
                      placeholder={t('gmailRefreshTokenPlaceholder')}
                      required
                    />
                  </div>
                </div>
              </div>
            ) : null}

            {formData.provider === 'SES' ? (
              <div className="space-y-4 rounded-lg border p-4">
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4" />
                  <h3 className="text-sm font-semibold">
                    {t('sesSectionTitle')}
                  </h3>
                </div>
                <div className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="ses-access-key-id">
                      {t('sesAccessKeyIdLabel')}
                    </Label>
                    <Input
                      id="ses-access-key-id"
                      value={formData.ses_access_key_id}
                      onChange={(event) =>
                        updateFormField('ses_access_key_id', event.target.value)
                      }
                      placeholder={t('sesAccessKeyIdPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="ses-secret-access-key">
                      {t('sesSecretAccessKeyLabel')}
                    </Label>
                    <Input
                      id="ses-secret-access-key"
                      type="password"
                      value={formData.ses_secret_access_key}
                      onChange={(event) =>
                        updateFormField(
                          'ses_secret_access_key',
                          event.target.value
                        )
                      }
                      placeholder={t('sesSecretAccessKeyPlaceholder')}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="ses-region">{t('sesRegionLabel')}</Label>
                    <Input
                      id="ses-region"
                      value={formData.ses_region}
                      onChange={(event) =>
                        updateFormField('ses_region', event.target.value)
                      }
                      placeholder={t('sesRegionPlaceholder')}
                      required
                    />
                  </div>
                </div>
              </div>
            ) : null}

            <div className="flex justify-end border-t pt-4">
              {canSubmitProfile ? (
                <Button type="submit" className="min-w-40">
                  {editMode ? t('saveChanges') : t('createProfile')}
                </Button>
              ) : (
                <Button
                  type="button"
                  className="min-w-40"
                  onClick={handleTest}
                  disabled={isTesting}
                >
                  {isTesting ? t('testing') : t('testProfile')}
                </Button>
              )}
            </div>
          </form>
        </ResizableSheetContent>
      </Sheet>

      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('deleteConfirmTitle')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('deleteConfirmDescription')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t('delete')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Page>
  );
}
