import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
import DateObject from "react-date-object";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import { Calendar } from "react-multi-date-picker";
import Button from "../../../../../components/Button";
import TaskDetailLabelCheckbox from "../labels/TaskDetailLabelCheckbox";
import type { TaskDateField } from "./types";
import { formatDateLabel } from "./utils";

type Props = {
  onClose: () => void;
  onSubmit: (data: { startDate: DateObject | null; endDate: DateObject | null }) => void;
  initialStartDate?: DateObject | null;
  initialEndDate?: DateObject | null;
  isSubmitting?: boolean;
};

const TaskDetailDateForm: FC<Props> = ({
  onClose,
  onSubmit,
  initialStartDate = null,
  initialEndDate = null,
  isSubmitting = false,
}) => {
  const { t } = useTranslation("global");
  const [startDate, setStartDate] = useState<DateObject | null>(initialStartDate);
  const [endDate, setEndDate] = useState<DateObject | null>(initialEndDate);
  const [startEnabled, setStartEnabled] = useState(Boolean(initialStartDate) || !initialEndDate);
  const [endEnabled, setEndEnabled] = useState(Boolean(initialEndDate));
  const [activeField, setActiveField] = useState<TaskDateField>("start");

  const calendarValue = (() => {
    if (startEnabled && endEnabled && startDate && endDate) {
      return [startDate, endDate];
    }
    if (activeField === "end" && endDate) return endDate;
    if (startDate) return startDate;
    return undefined;
  })();

  const handleCalendarChange = (value: DateObject | DateObject[] | null) => {
    if (!value) return;

    if (Array.isArray(value)) {
      const [start, end] = value;
      if (startEnabled) setStartDate(start);
      if (endEnabled) setEndDate(end ?? null);
      return;
    }

    if (activeField === "start" && startEnabled) {
      setStartDate(value);
      return;
    }

    if (activeField === "end" && endEnabled) {
      setEndDate(value);
    }
  };

  const handleStartToggle = () => {
    const next = !startEnabled;
    setStartEnabled(next);
    if (next) {
      setActiveField("start");
      return;
    }
    if (!endEnabled) {
      setEndEnabled(true);
      setActiveField("end");
    }
  };

  const handleEndToggle = () => {
    const next = !endEnabled;
    setEndEnabled(next);
    if (next) {
      setActiveField("end");
      return;
    }
    if (!startEnabled) {
      setStartEnabled(true);
      setActiveField("start");
    }
  };

  const canSubmit = (startEnabled && Boolean(startDate)) || (endEnabled && Boolean(endDate));

  const handleSubmit = () => {
    if (!canSubmit) return;
    onSubmit({
      startDate: startEnabled ? startDate : null,
      endDate: endEnabled ? endDate : null,
    });
  };

  return (
    <div className="flex flex-col gap-3">
      <div className="task-detail-date-calendar">
        <Calendar
          value={calendarValue}
          onChange={handleCalendarChange}
          calendar={persian}
          locale={persian_fa}
          range={startEnabled && endEnabled}
          className="w-full"
        />
      </div>

      <div className="flex flex-col gap-2">
        <div className="flex items-center gap-2">
          <span className="text-xs shrink-0 w-[72px]">{t("taskmanager.task_detail.start_date")}</span>
          <input
            readOnly
            value={formatDateLabel(startDate)}
            placeholder={t("taskmanager.select_date")}
            onFocus={() => setActiveField("start")}
            className="flex-1 h-8 text-xs rounded-xl border border-white bg-white/63 px-3 text-[#292D32] outline-none"
          />
          <TaskDetailLabelCheckbox
            checked={startEnabled}
            onToggle={handleStartToggle}
            ariaLabel={t("taskmanager.task_detail.start_date")}
          />
        </div>

        <div className="flex items-center gap-2">
          <span className="text-xs shrink-0 w-[72px]">{t("taskmanager.task_detail.end_date")}</span>
          <input
            readOnly
            value={formatDateLabel(endDate)}
            placeholder={t("taskmanager.select_date")}
            onFocus={() => setActiveField("end")}
            className="flex-1 h-8 text-xs rounded-xl border border-white bg-white/63 px-3 text-[#292D32] outline-none"
          />
          <TaskDetailLabelCheckbox
            checked={endEnabled}
            onToggle={handleEndToggle}
            ariaLabel={t("taskmanager.task_detail.end_date")}
          />
        </div>
      </div>

      <div className="flex justify-end gap-2">
        <Button
          type="button"
          onClick={onClose}
          disabled={isSubmitting}
          className="h-8 bg-[#E8E4F0] text-[#292D32] rounded-xl text-xs w-[95px]"
        >
          {t("cancel")}
        </Button>
        <Button
          type="button"
          onClick={handleSubmit}
          disabled={!canSubmit || isSubmitting}
          isLoading={isSubmitting}
          className="h-8 bg-[#292D32] text-white rounded-xl text-xs disabled:opacity-50 w-[95px]"
        >
          {t("taskmanager.task_detail.insert")}
        </Button>
      </div>
    </div>
  );
};

export default TaskDetailDateForm;
