"use client";

import { ErrorMessage, Form, FormikProps } from "formik";
import React, { useRef, useState } from "react";
import {
  UpdateMedicalPackageFormProps,
  UpdateMedicalPackageFormValues,
} from "./UpdateMedicalPackageForm";
import RichTextEditor, { RichTextEditorHandle } from "@/components/TextEditor";
import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import Loader from "@/components/Loader";
import Image from "next/image";
import DeleteFileButton from "@/components/DeleteFileButton";

export default function InnerUpdateMedicalPackageForm(
  props: FormikProps<UpdateMedicalPackageFormValues> &
    UpdateMedicalPackageFormProps,
) {
  const [isSub, setIsSub] = useState(props.preValues.parent_id ? true : false);
  const { setFieldValue} = props;
  const ref = useRef<RichTextEditorHandle>(null);
  const [refs] = useState(
    props.languages.map(() => JSON.parse(JSON.stringify(ref))),
  );

  const handleSave = () => {
    refs.forEach((r, i) => {
      setFieldValue(`translations.${i}.content`, r.current.getContent());
    });
    props.handleSubmit();
  };
  return (
    <Form className="space-y-8">
      <div className="border p-4 rounded-md space-y-4 bg-white">
        <Field>
          <FieldLabel>عکس شاخص</FieldLabel>
          <div
            className="relative"
            style={{ width: "300px", height: "300px", objectFit: "cover" }}
          >
            <DeleteFileButton
              type="image"
              fileKey={props.preValues.thumbnail.fileKey}
              fileUrl={props.preValues.thumbnail.fileUrl!}
            />
            <Image
              src={props.preValues.thumbnail.fileUrl!}
              fill
              alt={props.preValues.thumbnail.filename!}
            />
          </div>
        </Field>
      </div>
      {props.values.translations.map((tr, index) => {
        const lang = props?.languages.find((l) => l.id === tr.lang_id);

        return (
          <div
            key={tr.lang_id}
            className="border p-4 rounded-md space-y-4 bg-white"
          >
            <h4 className="font-semibold text-lg">
              ردیف برای زبان {lang?.title} ({lang?.slug})
            </h4>

            {/* First Name */}
            <Field>
              <FieldLabel htmlFor={`translations.${index}.title`}>
                عنوان
              </FieldLabel>
              <Input
                id={`translations.${index}.title`}
                placeholder="Title"
                name={`translations.${index}.title`}
                value={tr.title}
                onChange={(e) =>
                  setFieldValue(`translations.${index}.title`, e.target.value)
                }
              />
              <ErrorMessage
                className="text-xs text-red-500"
                component={"div"}
                name={`translations.${index}.title`}
              />
            </Field>

            {/* Last Name */}
            <Field>
              <FieldLabel htmlFor={`translations.${index}.content`}>
                محتوا
              </FieldLabel>
              <RichTextEditor value={tr.content ?? ""} ref={refs[index]} />
              <ErrorMessage
                className="text-xs text-red-500"
                component={"div"}
                name={`translations.${index}.content`}
              />
            </Field>
          </div>
        );
      })}
      <div className="border p-4 rounded-md  bg-white space-y-8">
        <FieldLabel>آیکون (کد svg را در این قسمت قرار دهید)</FieldLabel>
        <Textarea
          value={props.values.icon}
          onChange={(value) => setFieldValue("icon", value)}
        ></Textarea>
      </div>
      <div className="border p-4 rounded-md  bg-white space-y-8">
        <div className="flex items-center justify-between">
          <FieldLabel>آیا میخواهید زیر مجموعه شود</FieldLabel>
          <Switch
            dir="ltr"
            className="text-xl"
            defaultChecked={isSub}
            onCheckedChange={(checked) => setIsSub(checked)}
          />
        </div>
        {isSub && (
          <Field>
            <FieldLabel>انتخاب خدمت پزشکی والد</FieldLabel>
            <Select
              dir="rtl"
              value={
                props.values.parent_id ? String(props.values.parent_id) : ""
              }
              onValueChange={(value) =>
                setFieldValue(`parent_id`, value ? Number(value) : null)
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="انتخاب خدمت پزشکی" />
              </SelectTrigger>

              <SelectContent>
                {props?.parents?.map((exp) => {
                  // ترجمه مرتبط با همین زبان
                  const translation = exp.translations.find(
                    (t) => t.lang_id === 1,
                  );

                  return (
                    <SelectItem key={exp.id} value={String(exp.id)}>
                      {translation?.title}
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
          </Field>
        )}
      </div>
      <Button disabled={props.updatePending} type="button" onClick={handleSave}>
        {props.updatePending ? <Loader size="4" /> : "ثبت اطلاعات"}
      </Button>
    </Form>
  );
}
