import { Controller, useForm } from "react-hook-form";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import {
  LetterTemplate,
  LetterTemplatePayload,
} from "@/user-management/services/api/letterTemplateService";
import { TemplateEditor } from "@/super-admin/components/templates/components/TemplateEditor";
import { useHeaderFooterPresigned } from "@/record-management/components/hooks/useHeaderFooterPresigned";
import { useMemo, useState, useEffect } from "react";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Card, CardContent } from "@/shared/common/ui/card";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";

interface Props {
  unitId: string;
  template?: LetterTemplate | null;
  isSubmitting: boolean;
  onCancel: () => void;
  onSubmitCreate: (data: LetterTemplatePayload) => void;
}

export const LetterTemplateForm = ({
  unitId,
  template,
  isSubmitting,
  onCancel,
  onSubmitCreate,
}: Props) => {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const [selectedHeader, setSelectedHeader] = useState<string>("");
  const [selectedFooter, setSelectedFooter] = useState<string>("");

  const {
    register,
    handleSubmit,
    reset,
    control,
    setValue,
    watch,
    formState: { errors },
  } = useForm<LetterTemplatePayload>({
    defaultValues: {
      name: {
        en: template?.name?.en ?? "",
        am: template?.name?.am ?? "",
      },
      key: template?.key ?? "",
      subject: template?.subject ?? "",
      body: template?.body ?? "",
      sincerelyText: template?.sincerelyText ?? "",
      headerId: template?.headerId ?? "",
      footerId: template?.footerId ?? "",
      unitId,
    },
  });

  const { data: headerFooterData } = useHeaderFooterPresigned(unitId);
  const headers = useMemo(
    () => headerFooterData?.headers || [],
    [headerFooterData?.headers],
  );
  const footers = useMemo(
    () => headerFooterData?.footers || [],
    [headerFooterData?.footers],
  );

  const selectedHeaderId = watch("headerId");
  const selectedFooterId = watch("footerId");

  // Update header preview when selection changes
  useEffect(() => {
    if (headers.length && selectedHeaderId) {
      const header = headers.find((h) => h.id === selectedHeaderId);
      if (header) {
        setSelectedHeader(
          `<div class="letter-header"><img src="${header.presigned}" alt="Header" style="width: 100%; max-height: 150px;" /></div>`,
        );
      }
    } else {
      setSelectedHeader("");
    }
  }, [headers, selectedHeaderId]);

  // Update footer preview when selection changes
  useEffect(() => {
    if (footers.length && selectedFooterId) {
      const footer = footers.find((f) => f.id === selectedFooterId);
      if (footer) {
        setSelectedFooter(
          `<div class="letter-footer"><img src="${footer.presigned}" alt="Footer" style="width: 100%; max-height: 150px;" /></div>`,
        );
      }
    } else {
      setSelectedFooter("");
    }
  }, [footers, selectedFooterId]);

  const onSubmit = (values: LetterTemplatePayload) => {
    onSubmitCreate(values);
    if (!template) {
      reset();
    }
  };

  // Header options for select
  const headerOptions = headers.map((header) => ({
    label: localizedName(header.name),
    value: header.id,
  }));

  // Footer options for select
  const footerOptions = footers.map((footer) => ({
    label: localizedName(footer.name),
    value: footer.id,
  }));

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg p-8 shadow-sm space-y-8"
    >
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t("template.key", "Template Key")}
          </label>
          <Input
            placeholder={t("template.keyPlaceholder", "Template Key")}
            {...register("key", {
              required: t("template.keyRequired", "Template key is required"),
            })}
          />
          {errors.key && (
            <p className="text-red-500 text-sm mt-1">{errors.key.message}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t("template.subject", "Subject")}
          </label>
          <Input
            placeholder={t("template.subjectPlaceholder", "Subject")}
            {...register("subject", {
              required: t("template.subjectRequired", "Subject is required"),
            })}
          />
          {errors.subject && (
            <p className="text-red-500 text-sm mt-1">
              {errors.subject.message}
            </p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t("template.englishName", "English Name")}
          </label>
          <Input
            placeholder={t("template.englishNamePlaceholder", "English Name")}
            {...register("name.en", {
              required: t(
                "template.englishNameRequired",
                "English name is required",
              ),
            })}
          />
          {errors.name?.en && (
            <p className="text-red-500 text-sm mt-1">
              {errors.name.en.message}
            </p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t("template.amharicName", "Amharic Name")}
          </label>
          <Input
            placeholder={t("template.amharicNamePlaceholder", "Amharic Name")}
            {...register("name.am", {
              required: t(
                "template.amharicNameRequired",
                "Amharic name is required",
              ),
            })}
          />
          {errors.name?.am && (
            <p className="text-red-500 text-sm mt-1">
              {errors.name.am.message}
            </p>
          )}
        </div>

        {/* Header Selection */}
        {headerOptions.length > 0 && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("template.header", "Header")}
            </label>
            <select
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              value={selectedHeaderId || ""}
              onChange={(e) => setValue("headerId", e.target.value)}
            >
              <option value="">{t("template.noHeader", "No Header")}</option>
              {headerOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        )}

        {/* Footer Selection */}
        {footerOptions.length > 0 && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("template.footer", "Footer")}
            </label>
            <select
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              value={selectedFooterId || ""}
              onChange={(e) => setValue("footerId", e.target.value)}
            >
              <option value="">{t("template.noFooter", "No Footer")}</option>
              {footerOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Header Preview */}
      {selectedHeader && (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-4">
            <p className="text-sm font-medium text-muted-foreground mb-2">
              {t("template.headerPreview", "Header Preview")}
            </p>
            <div
              className="bg-muted rounded-lg p-4 border-2 border-dashed border-muted-foreground/20"
              dangerouslySetInnerHTML={{ __html: selectedHeader }}
            />
          </CardContent>
        </Card>
      )}

      {/* Body Section */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          {t("template.body", "Body")}
          <span className="text-destructive ml-1">*</span>
        </label>
        <Controller
          name="body"
          control={control}
          rules={{ required: t("template.bodyRequired", "Body is required") }}
          render={({ field, fieldState }) => (
            <>
              <TemplateEditor
                value={field.value}
                onEditorChange={field.onChange}
                placeholders={[
                  {
                    key: "delegatorName",
                    label: t("placeholder.delegatorName", "Delegator Name"),
                  },
                  {
                    key: "delegatorDepartment",
                    label: t(
                      "placeholder.delegatorDepartment",
                      "Delegator Department",
                    ),
                  },
                  {
                    key: "delegateeName",
                    label: t("placeholder.delegateeName", "Delegatee Name"),
                  },
                  {
                    key: "delegateeDepartment",
                    label: t(
                      "placeholder.delegateeDepartment",
                      "Delegatee Department",
                    ),
                  },
                  {
                    key: "startDate",
                    label: t("placeholder.startDate", "Start Date"),
                  },
                  {
                    key: "endDate",
                    label: t("placeholder.endDate", "End Date"),
                  },
                  {
                    key: "startDateTime",
                    label: t("placeholder.startDateTime", "Start Date & Time"),
                  },
                  {
                    key: "endDateTime",
                    label: t("placeholder.endDateTime", "End Date & Time"),
                  },
                ]}
              />
              {fieldState.invalid && (
                <p className="text-red-500 text-sm mt-1">
                  {fieldState.error?.message}
                </p>
              )}
            </>
          )}
        />
      </div>

      {/* Footer Preview */}
      {selectedFooter && (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-4">
            <p className="text-sm font-medium text-muted-foreground mb-2">
              {t("template.footerPreview", "Footer Preview")}
            </p>
            <div
              className="bg-muted rounded-lg p-4 border-2 border-dashed border-muted-foreground/20"
              dangerouslySetInnerHTML={{ __html: selectedFooter }}
            />
          </CardContent>
        </Card>
      )}

      {/* Sincerely Text */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          {t("template.sincerelyText", "Sincerely Text")}
        </label>
        <Input
          placeholder={t("template.sincerelyTextPlaceholder", "Sincerely Text")}
          {...register("sincerelyText")}
        />
      </div>

      {/* Action Buttons */}
      <div className="flex gap-2 pt-4 justify-end">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting
            ? t("common.saving", "Saving...")
            : template
              ? t("common.update", "Update")
              : t("common.save", "Save")}
        </Button>
        <Button type="button" variant="outline" onClick={onCancel}>
          {t("common.cancel", "Cancel")}
        </Button>
      </div>
    </form>
  );
};
