"use client";
import { ErrorMessage, Form, FormikProps } from "formik";
import React, { useRef, useState } from "react";

import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { UpdateDoctorFormProps } from "./UpdateDoctorForm";
import { CreateDoctorFormValues } from "../create/CreateDoctorForm";
import DeleteFileButton from "@/components/DeleteFileButton";
import Image from "next/image";
import RichTextEditor, { RichTextEditorHandle } from "@/components/TextEditor";

export default function InnerUpdateDoctorForm(
  props: FormikProps<CreateDoctorFormValues> & UpdateDoctorFormProps,
) {
  const { setFieldValue, ...rest } = props;
  const bioRef = useRef<RichTextEditorHandle>(null);
  const [bioRefs, setBioRefs] = useState(
    props.languages.map(() => JSON.parse(JSON.stringify(bioRef))),
  );

  const excerptRef = useRef<RichTextEditorHandle>(null);
  const [excerptRefs, setExcerptRefs] = useState(
    props.languages.map(() => JSON.parse(JSON.stringify(excerptRef))),
  );
  const handleSave = () => {
    bioRefs.forEach((r, i) => {
      setFieldValue(`translations.${i}.bio`, r.current.getContent());
    });
    excerptRefs.forEach((r, i) => {
      setFieldValue(`translations.${i}.excerpt`, r.current.getContent());
    });
    props.handleSubmit();
  };
  return (
    <Form className="space-y-4">
      <div className="border p-4 rounded-md space-y-4 bg-white">
        <Field>
          <FieldLabel>عکس شاخص</FieldLabel>
          <div
            className="relative rounded-3xl overflow-hidden object-fill"
            style={{ width: "300px", height: "300px", objectFit: "cover" }}
          >
            <DeleteFileButton
              type="image"
              fileKey={props?.preValues.image?.fileKey}
              fileUrl={props?.preValues.image?.fileUrl}
            />
            <Image
              src={props?.preValues.image?.fileUrl ?? "/"}
              fill
              objectFit="cover"
              alt={props?.preValues.image?.filename}
            />
          </div>
        </Field>
        <Field>
          <FieldLabel htmlFor={`email`}>ایمیل</FieldLabel>
          <Input
            id={`email`}
            placeholder="Email"
            name={`email`}
            value={props.values.email}
            onChange={(e) => setFieldValue(`email`, e.target.value)}
          />
          <ErrorMessage
            className="text-xs text-red-500"
            component={"div"}
            name={`email`}
          />
        </Field>
        <Field>
          <FieldLabel htmlFor={`phone`}>شماره موبایل</FieldLabel>
          <Input
            id={`phone`}
            placeholder="Mobile number"
            name={`phone`}
            value={props.values.phone}
            onChange={(e) => setFieldValue(`phone`, e.target.value)}
          />
          <ErrorMessage
            className="text-xs text-red-500"
            component={"div"}
            name={`phone`}
          />
        </Field>
        <Field>
          <FieldLabel htmlFor={`medicalNumber`}>شماره نظام پزشکی</FieldLabel>
          <Input
            id={`medicalNumber`}
            placeholder="Medical Number"
            name={`medicalNumber`}
            value={props.values.medicalNumber}
            onChange={(e) => setFieldValue(`medicalNumber`, e.target.value)}
          />
          <ErrorMessage
            className="text-xs text-red-500"
            component={"div"}
            name={`medicalNumber`}
          />
        </Field>
        <Field>
          <FieldLabel>تخصص</FieldLabel>

          <Select
            dir="rtl"
            value={
              props.values.expertiseId ? String(props.values.expertiseId) : ""
            }
            onValueChange={(value) =>
              setFieldValue(`expertiseId`, value ? Number(value) : null)
            }
          >
            <SelectTrigger>
              <SelectValue placeholder="انتخاب تخصص" />
            </SelectTrigger>

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

                return (
                  <SelectItem key={exp.id} value={String(exp.id)}>
                    {translation?.displayName ?? exp.slug}
                  </SelectItem>
                );
              })}
            </SelectContent>
          </Select>

          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`expertiseId`}
          />
        </Field>
      </div>
      {props.values.translations &&
        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}.firstName`}>
                  نام
                </FieldLabel>
                <Input
                  id={`translations.${index}.firstName`}
                  placeholder="First Name"
                  name={`translations.${index}.firstName`}
                  value={tr.firstName}
                  onChange={(e) =>
                    setFieldValue(
                      `translations.${index}.firstName`,
                      e.target.value,
                    )
                  }
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component={"div"}
                  name={`translations.${index}.firstName`}
                />
              </Field>

              {/* Last Name */}
              <Field>
                <FieldLabel htmlFor={`translations.${index}.lastName`}>
                  نام خانوادگی
                </FieldLabel>
                <Input
                  id={`translations.${index}.lastName`}
                  placeholder="Last Name"
                  name={`translations.${index}.lastName`}
                  value={tr.lastName}
                  onChange={(e) =>
                    setFieldValue(
                      `translations.${index}.lastName`,
                      e.target.value,
                    )
                  }
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component={"div"}
                  name={`translations.${index}.lastName`}
                />
              </Field>
              <Field>
                <FieldLabel htmlFor={`translations.${index}.excerpt`}>
                  متن کوتاه پروفایل ( برای نمایش در کارت ها )
                </FieldLabel>
                <RichTextEditor value={tr.excerpt} ref={excerptRefs[index]} />

                <ErrorMessage
                  className="text-xs text-red-500"
                  component={"div"}
                  name={`translations.${index}.excerpt`}
                />
              </Field>
              <Field>
                <FieldLabel htmlFor={`translations.${index}.bio`}>
                  بایوگرافی
                </FieldLabel>
                <RichTextEditor value={tr.bio} ref={bioRefs[index]} />

                <ErrorMessage
                  className="text-xs text-red-500"
                  component={"div"}
                  name={`translations.${index}.bio`}
                />
              </Field>
              {/* Position */}
              {/* <Field>
                <FieldLabel htmlFor={`translations.${index}.position`}>
                  سمت
                </FieldLabel>
                <Input
                  id={`translations.${index}.position`}
                  placeholder="Position"
                  name={`translations.${index}.position`}
                  value={tr.position}
                  onChange={(e) =>
                    setFieldValue(
                      `translations.${index}.position`,
                      e.target.value,
                    )
                  }
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component={"div"}
                  name={`translations.${index}.position`}
                />
              </Field> */}
            </div>
          );
        })}
      <Button type="submit">ثبت اطلاعات</Button>
    </Form>
  );
}
