import { Controller, useForm } from "react-hook-form";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { CreateTemplateTypes } from "../types/templateTypes";
import { Editor } from "@/record-management/common/editor/rte";
import { TemplateEditor } from "./TemplateEditor";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
interface Props {
  template?: CreateTemplateTypes | null;
  isSubmitting: boolean;
  onCancel: () => void;
  onSubmitCreate: (data: CreateTemplateTypes) => void;
}

const editorApiKey = import.meta.env.VITE_EDITOR_API_KEY || "";

export const TemplateForm = ({
  template,
  isSubmitting,
  onCancel,
  onSubmitCreate,
}: Props) => {
  const {
    register,
    handleSubmit,
    reset,
    control,
    formState: { errors },
  } = useForm<CreateTemplateTypes>({
    defaultValues: {
      name: {
        en: template?.name?.en ?? "",
        am: template?.name?.am ?? "",
      },
      key: template?.key ?? "",
      subject: template?.subject ?? "",
      body: template?.body ?? "",
      sincerelyText: template?.sincerelyText ?? "",
      locale: template?.locale ?? "en",
    },
  });

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

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-8 shadow-sm dark:shadow-gray-900/50 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">
            Template Key
          </label>
          <Input
            placeholder="Template Key"
            {...register("key", { required: "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">
            Subject
          </label>
          <Input
            placeholder="Subject"
            {...register("subject", { required: "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">
            English Name
          </label>
          <Input
            placeholder="English Name"
            {...register("name.en", { required: "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">
            Amharic Name
          </label>
          <Input
            placeholder="Amharic Name"
            {...register("name.am", { required: "Amharic name is required" })}
          />
          {errors.name?.am && (
            <p className="text-red-500 text-sm mt-1">
              {errors.name.am.message}
            </p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Language
          </label>
          <Controller
            name="locale"
            control={control}
            rules={{ required: "Language is required" }}
            render={({ field }) => (
              <Select value={field.value} onValueChange={field.onChange}>
                <SelectTrigger>
                  <SelectValue placeholder="Select Language" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="en">English</SelectItem>
                  <SelectItem value="am">Amharic</SelectItem>
                </SelectContent>
              </Select>
            )}
          />
          {errors.locale && (
            <p className="text-red-500 text-sm mt-1">{errors.locale.message}</p>
          )}
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          Body
        </label>
        <Controller
          name="body"
          control={control}
          rules={{ required: true }}
          render={({ field, fieldState }) => (
            <>
              <TemplateEditor
                value={field.value}
                onEditorChange={field.onChange}
                apiKey={editorApiKey}
                placeholders={[
                  { key: "delegatorName", label: "Delegator Name" },
                  { key: "delegatorDepartment", label: "Delegator Department" },
                  { key: "delegateeName", label: "Delegatee Name" },
                  { key: "delegateeDepartment", label: "Delegatee Department" },
                  { key: "startDate", label: "Start Date" },
                  { key: "endDate", label: "End Date" },
                  { key: "startDateTime", label: "Start Date & Time" },
                  { key: "endDateTime", label: "End Date & Time" },
                ]}
              />
              {fieldState.invalid && (
                <p className="text-red-500 text-sm mt-1">Body is required</p>
              )}
            </>
          )}
        />
      </div>
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          Sincerely Text
        </label>
        <Input placeholder="Sincerely Text" {...register("sincerelyText")} />
      </div>

      <div className="flex gap-2 pt-4 justify-end">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? "Saving..." : template ? "Update" : "Save"}
        </Button>
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
      </div>
    </form>
  );
};
