"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import SelectBox from "@/components/elements/SelectBox";
import {
  ProjectFormData,
  ProjectRoleForm,
  useProjectForm,
} from "@/contexts/ProjectFormContext";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import DatePicker from "react-multi-date-picker";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import Image from "next/image";
import RoleModal from "./RoleModal";
import {
  PROJECT_FIELD_CLASS,
  PROJECT_FIELD_ERROR_CLASS,
} from "@/lib/projectFormStyles";

const PAYMENT_OPTIONS = [
  "monthly",
  "daily",
  "hourly",
  "commission",
  "negotiable",
] as const;

const COLLAB_OPTIONS = [
  "full_time",
  "part_time",
  "project",
  "internship",
] as const;

const EXPERIENCE_OPTIONS = [
  "none",
  "lt1",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "gt10",
] as const;

const Step3 = ({
  nextStep,
}: {
  nextStep: (values: Partial<ProjectFormData>) => void;
}) => {
  const { t } = useTranslation("common");
  const { formData } = useProjectForm();
  const [roles, setRoles] = useState<ProjectRoleForm[]>(formData.roles || []);
  const [showRoleModal, setShowRoleModal] = useState(false);
  const [roleError, setRoleError] = useState("");

  const validationSchema = useMemo(
    () =>
      Yup.object({
        offerPrice: Yup.string().required(
          t("projects.newProject.validation.budgetRequired")
        ),
        paymentMethod: Yup.string().required(
          t("projects.newProject.validation.paymentMethodRequired")
        ),
        projectTime: Yup.string().required(
          t("projects.newProject.validation.projectTimeRequired")
        ),
        startDate: Yup.string().required(
          t("projects.newProject.validation.startDateRequired")
        ),
        workHoursStart: Yup.string().required(
          t("projects.newProject.validation.workHoursRequired")
        ),
        workHoursEnd: Yup.string().required(
          t("projects.newProject.validation.workHoursRequired")
        ),
        collaborationType: Yup.string().required(
          t("projects.newProject.validation.collaborationRequired")
        ),
        experience: Yup.string(),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      offerPrice: formData.offerPrice || "",
      paymentMethod: formData.paymentMethod || "",
      projectTime: formData.projectTime || "",
      startDate: formData.startDate || "",
      workHoursStart: formData.workHoursStart || "",
      workHoursEnd: formData.workHoursEnd || "",
      collaborationType: formData.collaborationType || "",
      experience: formData.experience || "",
    },
    enableReinitialize: true,
    validationSchema,
    onSubmit: (values) => {
      if (!roles.length) {
        setRoleError(t("projects.newProject.validation.roleRequired"));
        return;
      }
      nextStep({
        ...values,
        roles,
        expertise: roles[0]?.expertise || null,
        subExpertise: roles[0]?.subExpertise || [],
      });
    },
  });

  const handleAddRole = (role: ProjectRoleForm) => {
    if (roles.length >= 5) {
      setRoleError(t("projects.newProject.validation.maxRoles"));
      return;
    }
    setRoles((prev) => [...prev, role]);
    setRoleError("");
  };

  const removeRole = (id: string) => {
    setRoles((prev) => prev.filter((r) => r.id !== id));
  };

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex w-full flex-col items-center gap-2 text-sm"
    >
      <h6 className="mb-2 text-xl font-bold">{t("projects.newProject.title")}</h6>

      <RoundedButton
        type="button"
        variant="primary"
        className="w-full max-w-sm py-2"
        onClick={() => setShowRoleModal(true)}
        disabled={roles.length >= 5}
      >
        {t("projects.newProject.selectRole")}
      </RoundedButton>

      {roles.length > 0 ? (
        <div className="mt-2 flex w-full flex-col gap-2">
          {roles.map((role) => (
            <div
              key={role.id}
              className="flex items-center justify-between rounded-2xl border border-border-secondary-light px-3 py-2 dark:border-border-secondary-dark"
            >
              <div>
                <p className="font-semibold">{role.expertise}</p>
                <p className="text-xs text-neutral-500">
                  {role.subExpertise.join(" _ ")} · {role.numberOfPerson}{" "}
                  {t("projects.newProject.person")}
                </p>
              </div>
              <button
                type="button"
                className="text-xs text-red-500"
                onClick={() => removeRole(role.id)}
              >
                {t("projects.newProject.removeRole")}
              </button>
            </div>
          ))}
        </div>
      ) : null}
      {roleError ? <p className="text-red-500">{roleError}</p> : null}

      <hr className="my-2 w-full" />

      <RoundedInput
        className={`mt-2 max-w-full text-xs ${
          formik.touched.offerPrice && formik.errors.offerPrice
            ? PROJECT_FIELD_ERROR_CLASS
            : PROJECT_FIELD_CLASS
        }`}
        type="number"
        placeholder={t("projects.newProject.fields.budgetToman")}
        {...formik.getFieldProps("offerPrice")}
      />
      {formik.touched.offerPrice && formik.errors.offerPrice && (
        <p className="text-red-500">{formik.errors.offerPrice}</p>
      )}

      <SelectBox
        className={`mt-2 w-full max-w-full ${PROJECT_FIELD_CLASS}`}
        value={formik.values.paymentMethod}
        onChange={(e) => formik.setFieldValue("paymentMethod", e.target.value)}
      >
        <option value="">
          {t("projects.newProject.fields.paymentMethod")}
        </option>
        {PAYMENT_OPTIONS.map((key) => (
          <option key={key} value={key}>
            {t(`projects.newProject.paymentMethods.${key}`)}
          </option>
        ))}
      </SelectBox>
      {formik.touched.paymentMethod && formik.errors.paymentMethod && (
        <p className="text-red-500">{formik.errors.paymentMethod}</p>
      )}

      <div className="relative mt-2 w-full">
        <RoundedInput
          className={`max-w-full text-xs ${PROJECT_FIELD_CLASS}`}
          type="text"
          placeholder={t("projects.newProject.fields.projectDuration")}
          {...formik.getFieldProps("projectTime")}
        />
        <span className="absolute left-5 top-2 text-gray-400">
          ({t("projects.days")})
        </span>
      </div>
      {formik.touched.projectTime && formik.errors.projectTime && (
        <p className="text-red-500">{formik.errors.projectTime}</p>
      )}

      <div className="project-date-field relative mt-2 w-full">
        <DatePicker
          calendar={persian}
          locale={persian_fa}
          value={formik.values.startDate}
          onChange={(value) => {
            formik.setFieldValue(
              "startDate",
              value?.format("YYYY/MM/DD") || ""
            );
          }}
          calendarPosition="bottom-center"
          placeholder={t("projects.newProject.fields.startDate")}
          containerClassName="w-full"
          inputClass={`w-full max-w-full h-10 rounded-3xl bg-secondary-light px-12 text-center font-medium text-xs dark:bg-secondary-dark ${PROJECT_FIELD_CLASS}`}
          style={{ width: "100%" }}
        />
        <span className="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2">
          <Image
            width={22}
            height={22}
            alt=""
            src="/images/icons/calendar.svg"
          />
        </span>
      </div>
      {formik.touched.startDate && formik.errors.startDate && (
        <p className="text-red-500">{formik.errors.startDate}</p>
      )}

      <div className="mt-2 grid w-full grid-cols-2 gap-2">
        <RoundedInput
          type="time"
          className={`text-xs ${PROJECT_FIELD_CLASS}`}
          placeholder={t("projects.newProject.fields.workStart")}
          {...formik.getFieldProps("workHoursStart")}
        />
        <RoundedInput
          type="time"
          className={`text-xs ${PROJECT_FIELD_CLASS}`}
          placeholder={t("projects.newProject.fields.workEnd")}
          {...formik.getFieldProps("workHoursEnd")}
        />
      </div>
      {(formik.touched.workHoursStart && formik.errors.workHoursStart) ||
      (formik.touched.workHoursEnd && formik.errors.workHoursEnd) ? (
        <p className="text-red-500">
          {formik.errors.workHoursStart || formik.errors.workHoursEnd}
        </p>
      ) : null}

      <SelectBox
        className={`mt-2 w-full max-w-full ${PROJECT_FIELD_CLASS}`}
        value={formik.values.collaborationType}
        onChange={(e) =>
          formik.setFieldValue("collaborationType", e.target.value)
        }
      >
        <option value="">
          {t("projects.newProject.fields.collaborationType")}
        </option>
        {COLLAB_OPTIONS.map((key) => (
          <option key={key} value={key}>
            {t(`projects.newProject.collaborationTypes.${key}`)}
          </option>
        ))}
      </SelectBox>
      {formik.touched.collaborationType && formik.errors.collaborationType && (
        <p className="text-red-500">{formik.errors.collaborationType}</p>
      )}

      <SelectBox
        className={`mt-2 w-full max-w-full ${PROJECT_FIELD_CLASS}`}
        value={formik.values.experience}
        onChange={(e) => formik.setFieldValue("experience", e.target.value)}
      >
        <option value="">
          {t("projects.newProject.fields.experienceOptional")}
        </option>
        {EXPERIENCE_OPTIONS.map((key) => (
          <option key={key} value={key}>
            {t(`projects.newProject.experienceOptions.${key}`)}
          </option>
        ))}
      </SelectBox>

      <RoundedButton type="submit" variant="primary" className="mt-4 px-8 py-2">
        {t("projects.newProject.submitContinue")}
      </RoundedButton>

      <RoleModal
        isOpen={showRoleModal}
        onClose={() => setShowRoleModal(false)}
        onSave={handleAddRole}
      />
    </form>
  );
};

export default Step3;
