import FormRenderer from '@/components/common/form-renderer';
import PageHeading from '@/components/common/page-heading';
import LoaderIcon from '@/components/icons/loader-icon';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { getEmailTemplateFields } from '@/data/forms/email-template-fields';
import { updateRequest } from '@/data/request/update-request';
import { useApiSWR } from '@/hooks/useSWR';
import {
  emailTemplateSchema,
  TEmailTemplate,
  TEmailTemplateInput,
} from '@/schema/email-template-schema';
import { FormFieldType } from '@/types/form-field-type';
import { zodResolver } from '@hookform/resolvers/zod';
import { router, usePage } from '@inertiajs/react';
import { CheckIcon, PlusIcon, XIcon } from '@phosphor-icons/react';
import { useEffect, useState, useTransition } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

export type TEmailTemplateActionApi = {
  label?: string | null;
  type?: 'link' | 'button' | string | null;
  url?: string | null;
};

const UpdateEmailTemplates = () => {
  const [isPending, startTransition] = useTransition();
  const [copied, setCopied] = useState<string | null>(null);
  const page = usePage();
  const templateId = page.url.split('/')[3];

  type TEmailTemplateApiData = {
    name: string;
    slug: string;
    subject: string;
    title: string;
    body: string;
    footer: string;
    is_active: boolean;
    actions: TEmailTemplateActionApi[];
    available_variables: string[];
  };

  const { data, isLoading, mutate } = useApiSWR<TEmailTemplateApiData>(
    `/admin/templates/${templateId}`,
  );

  const { t } = useTranslation();

  const form = useForm<TEmailTemplateInput>({
    resolver: zodResolver(emailTemplateSchema),
    defaultValues: {
      name: '',
      slug: '',
      subject: '',
      title: '',
      body: '',
      footer: '',
      is_active: true,
      actions: [],
    },
    mode: 'onSubmit',
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'actions',
  });

  const formFields = getEmailTemplateFields();

  useEffect(() => {
    if (!data) return;

    form.reset({
      name: data?.name ?? '',
      slug: data?.slug ?? '',
      subject: data?.subject ?? '',
      title: data?.title ?? '',
      body: data?.body ?? '',
      footer: data?.footer ?? '',
      is_active: Boolean(data?.is_active),
      actions: Array.isArray(data?.actions)
        ? data.actions.map((a: TEmailTemplateActionApi) => ({
            label: a?.label ?? '',
            type: a?.type === 'link' ? 'link' : 'button',
            url: a?.url ?? '',
          }))
        : [],
    });
  }, [data, form]);

  const handleCopy = async (variable: string) => {
    const value = `{{${variable}}}`;

    await navigator.clipboard.writeText(value);

    setCopied(variable);

    setTimeout(() => {
      setCopied(null);
    }, 1500);
  };

  const onSubmit = (values: TEmailTemplateInput) => {
    const parsed: TEmailTemplate = emailTemplateSchema.parse(values);

    startTransition(async () => {
      const res = await updateRequest({
        url: `/api/admin/templates/${templateId}`,
        formData: parsed,
      });

      if (res?.success) {
        toast.success(t(res?.message));
        mutate();
        router.visit('/admin/email-templates');
      }
    });
  };

  if (isLoading)
    return (
      <div className="flex h-96 w-full items-center justify-center gap-2">
        <LoaderIcon />
        {t('Loading...')}
      </div>
    );

  return (
    <div className="mx-auto max-w-5xl">
      <PageHeading
        title={t('Update {{name}}', {
          name: data?.name || t('Email Template'),
        })}
        description={t(
          'Modify the settings and content of the selected email template.',
        )}
        backButton
      />

      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-4 rounded-xl bg-white p-6 shadow-box"
        >
          {formFields?.map((field: FormFieldType) => (
            <FormRenderer form={form} key={field.name} item={field} />
          ))}

          {Array.isArray(data?.available_variables) &&
            data.available_variables.length > 0 && (
              <div className="rounded-xl border border-black/10 bg-black/2 p-4">
                <div className="mb-2 text-sm font-medium">
                  {t('Available Variables')}
                </div>
                <div className="flex flex-wrap gap-2">
                  {data.available_variables.map((v: string) => (
                    <Badge
                      key={v}
                      onClick={() => handleCopy(v)}
                      className={`cursor-pointer rounded-lg border px-2.5 py-1 text-xs font-medium transition-all active:scale-95 ${
                        copied === v
                          ? 'border-success bg-success/10 text-success'
                          : 'border-black/10 bg-white hover:bg-black/5'
                      } `}
                    >
                      {copied === v ? t('Copied!') : `{{${v}}}`}
                    </Badge>
                  ))}
                </div>
                <p className="mt-2 text-xs text-black/60">
                  {t(
                    'Click any variable above to copy it. You can use these placeholders in the subject, title, body, footer, or action labels.',
                  )}{' '}
                  {t('For example:')}{' '}
                  <span className="font-medium">{'{{first_name}}'}</span>.
                </p>
              </div>
            )}

          <Separator />

          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-base font-semibold">{t('Actions')}</h3>
              <p className="text-sm text-black/60">
                {t('Add buttons/links shown in the email template.')}
              </p>
            </div>

            <Button
              type="button"
              variant="outline"
              onClick={() => append({ label: '', type: 'button', url: '' })}
              className="gap-2"
            >
              <PlusIcon weight="bold" />
              {t('Add Action')}
            </Button>
          </div>

          {fields.length === 0 ? (
            <div className="rounded-xl border border-dashed border-black/15 p-6 text-center text-sm text-black/60">
              {t('No actions added yet.')}
            </div>
          ) : (
            <div className="space-y-3">
              {fields.map((item, index) => (
                <div
                  key={item.id}
                  className="flex flex-col gap-3 rounded-xl border border-black/10 p-4 md:flex-row"
                >
                  <FormField
                    control={form.control}
                    name={`actions.${index}.label`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Action Label')}</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            placeholder={t('Visit Dashboard')}
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`actions.${index}.url`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Action URL')}</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            placeholder="/dashboard"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`actions.${index}.type`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Type')}</FormLabel>
                        <FormControl>
                          <Select
                            value={field.value}
                            onValueChange={field.onChange}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={t('Select type')} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="button">
                                {t('Button')}
                              </SelectItem>
                              <SelectItem value="link">{t('Link')}</SelectItem>
                            </SelectContent>
                          </Select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="flex items-end">
                    <Button
                      type="button"
                      variant="outline"
                      className="h-11 gap-2 border-destructive bg-destructive/10 text-destructive"
                      onClick={() => remove(index)}
                    >
                      <XIcon weight="bold" />
                      {t('Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}

          <Separator />

          <div className="flex justify-end gap-3 pt-4">
            <Button
              type="submit"
              variant="default"
              className="capitalize"
              loading={isPending}
            >
              <CheckIcon weight="bold" />
              {t('Update Template')}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
};

UpdateEmailTemplates.title = 'Update Email Template';

export default UpdateEmailTemplates;
