"use client";
import {ErrorMessage, Form, FormikProps} from "formik";
import React, {useRef, useState} from "react";
import {
  CreateTransferTeamFormProps,
  CreateTransferTeamFormValues,
} from "./CreateTransferTeamForm";
import {Field, FieldLabel} from "@/components/ui/field";
import {Input} from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {Button} from "@/components/ui/button";
import {Plus, Trash} from "lucide-react";
import RichTextEditor, {RichTextEditorHandle} from "@/components/TextEditor";
import {toast} from "react-toastify";

export default function InnerCreateTransferTeamForm(
  props: FormikProps<CreateTransferTeamFormValues> & CreateTransferTeamFormProps
) {
  const introductionRef = useRef<RichTextEditorHandle>(null);
  const servicesRef = useRef<RichTextEditorHandle>(null);
  const dutiesRef = useRef<RichTextEditorHandle>(null);

  const {setFieldValue, ...rest} = props;
  const [members, setMembers] = useState<
    {id: string | null; name: string; index: string}[]
  >([]);

  const handleSave = () => {
    const introductionHtml = introductionRef.current?.getContent();
    const servicesHtml = servicesRef.current?.getContent();
    const dutiesHtml = dutiesRef.current?.getContent();
    props.setFieldValue("introduction", introductionHtml);
    props.setFieldValue("services", servicesHtml);
    props.setFieldValue("duties", dutiesHtml);
    props.values.members = members;
    props.submitForm();
  };

  const handleValueChange = (value: string, index: string) => {
    const memberSelected = props.members.find((item) => item.id === +value)!;
    const rowSelected = members.find((item) => item.index === index)!;

    rowSelected.id = String(memberSelected.id!);
    rowSelected.name = memberSelected.slug;
  };
  return (
    <Form className="space-y-4">
      <div className="border p-4 rounded-md space-y-10 bg-white">
        <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>نام تیم</FieldLabel>
          <Input
            value={props.values.name}
            onChange={(e) => setFieldValue("name", e.target.value)}
          />
          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`name`}
          />
        </Field>
        <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>متن معرفی تیم</FieldLabel>
          <RichTextEditor
            ref={introductionRef}
            value={props.values.introduction}
          />
          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`introduction`}
          />
        </Field>
        <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>متن خدمات تیم</FieldLabel>
          <RichTextEditor ref={servicesRef} value={props.values.services} />
          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`services`}
          />
        </Field>
        <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>متن وظایف تیم</FieldLabel>
          <RichTextEditor ref={dutiesRef} value={props.values.duties} />
          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`duties`}
          />
        </Field>
        <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>انتخاب عضو</FieldLabel>

          <div className="space-y-5">
            {members?.map((item, index) => (
              <div key={item?.index} className="flex items-center gap-5">
                <Select
                  dir="rtl"
                  onValueChange={(value) => {
                    return handleValueChange(value, item.index);
                  }}
                >
                  <SelectTrigger className="flex-1 w-full">
                    <SelectValue placeholder="انتخاب کنید " />
                  </SelectTrigger>

                  <SelectContent className="flex-1 w-full">
                    {props.members?.length > 0 &&
                      props?.members?.map((member) => {
                        // ترجمه مرتبط با همین زبان
                        const translation = member.translations.find(
                          (t) => t.lang_id === 1
                        );

                        return (
                          <SelectItem key={member.id} value={String(member.id)}>
                            {translation?.firstName} - {translation?.lastName}
                          </SelectItem>
                        );
                      })}
                  </SelectContent>
                </Select>
                <Button
                  type="button"
                  variant={"destructive"}
                  onClick={() => {
                    const filtered = members.filter((item2) => item2 !== item);
                    setMembers(filtered);
                  }}
                >
                  <Trash />
                </Button>
              </div>
            ))}
            <Button
              type="button"
              disabled={members.length > 3}
              onClick={() => {
                if (members.length > 3) {
                  toast.error("حداکثر اعضای تیم 4 نفر می باشد");
                  return;
                }
                const newMember = {
                  id: "",
                  name: "",
                  index: crypto.randomUUID(),
                };
                setMembers((prev) => [...prev, newMember]);
              }}
            >
              <Plus />
              افزودن عضو
            </Button>
          </div>

          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`members`}
          />
        </Field>
        {/* <Field className="border-b border-b-neutral-100 pb-10">
          <FieldLabel>انتخاب پکیج گردشگری</FieldLabel>

          <div className="space-y-5">
            {members?.map((item, index) => (
              <div key={item?.index} className="flex items-center gap-5">
                <Select dir="rtl" value={""}>
                  <SelectTrigger className="flex-1 w-full">
                    <SelectValue placeholder="انتخاب کنید " />
                  </SelectTrigger>

                  <SelectContent className="flex-1 w-full">
                    {props.packages?.length > 0 &&
                      props?.packages?.map((member) => {
                        // ترجمه مرتبط با همین زبان
                        const translation = member.translations.find(
                          (t) => t.lang_id === 1
                        );

                        return (
                          <SelectItem key={member.id} value={String(member.id)}>
                            {translation?.firstName} - {translation?.lastName}
                          </SelectItem>
                        );
                      })}
                  </SelectContent>
                </Select>
                <Button
                  type="button"
                  variant={"destructive"}
                  onClick={() => {
                    const filtered = members.filter((item2) => item2 !== item);
                    setMembers(filtered);
                  }}
                >
                  <Trash />
                </Button>
              </div>
            ))}
            <Button
              type="button"
              onClick={() => {
                const newMember = {
                  id: "",
                  name: "",
                  index: crypto.randomUUID(),
                };
                setMembers((prev) => [...prev, newMember]);
              }}
            >
              <Plus />
              افزودن پکیج
            </Button>
          </div>

          <ErrorMessage
            className="text-xs text-red-500"
            component="div"
            name={`members`}
          />
        </Field> */}
        <div>
          <Button type="button" onClick={handleSave}>
            ثبت نهایی
          </Button>
        </div>
      </div>
    </Form>
  );
}
