import { MyButtons } from '@/common';
import { Apis } from '@/gen/Apis';
import { AttendanceSchedulesStatusEnum } from '@/gen/Enums';
import { Calendar, message, Modal, Popconfirm, Select } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { useCallback, useEffect, useRef, useState } from 'react';

const yearOptions = Array.from({ length: 10 }, (_, i) => {
  const y = dayjs().year() - 5 + i;
  return { label: `${y}年`, value: y };
});

const monthOptions = Array.from({ length: 12 }, (_, i) => ({
  label: `${i + 1}月`,
  value: i,
}));

interface ScheduleItem {
  id: number;
  schedule_date: string;
  attendance_shifts_id?: number;
  attendance_shift?: { name: string; id: number };
  asset_projects_id?: number;
  status?: string;
}

export default function ViewCalendar({
  item,
  reload: reloadList,
}: {
  item: Record<string, any>;
  reload?: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [schedules, setSchedules] = useState<ScheduleItem[]>([]);
  const [currentMonth, setCurrentMonth] = useState(dayjs());
  const [shiftOptions, setShiftOptions] = useState<
    { label: string; value: number }[]
  >([]);
  const monthRef = useRef(dayjs());

  const employeeId = item?.company_employees_id;
  const projectId = item?.asset_projects_id;
  const organizationId = item?.organizations_id;
  const scheduleDates = item?.schedule_date;

  const fetchSchedules = useCallback(
    (month: Dayjs) => {
      const startDate = month.startOf('month').format('YYYY-MM-DD');
      const endDate = month.endOf('month').format('YYYY-MM-DD');
      Apis.Attendance.AttendanceSchedules.List({
        company_employees_id: employeeId,
        status: AttendanceSchedulesStatusEnum.Active.value,
        schedule_dates: [startDate, endDate],
        perPage: 100,
      } as any).then((res) => {
        const list: ScheduleItem[] = res?.data || [];
        const start = month.startOf('month');
        const end = month.endOf('month');
        const filtered = list.filter((s) => {
          const d = dayjs(s.schedule_date);
          return (
            (d.isAfter(start) || d.isSame(start, 'day')) &&
            (d.isBefore(end) || d.isSame(end, 'day'))
          );
        });
        setSchedules(filtered);
      });
    },
    [employeeId],
  );

  const reload = useCallback(() => {
    fetchSchedules(monthRef.current);
  }, [fetchSchedules]);

  const fetchShiftOptions = useCallback(() => {
    Apis.Attendance.AttendanceShifts.Select({}).then((res) => {
      const list = (res?.data || []) as { name: string; id: number }[];
      setShiftOptions(list.map((s) => ({ label: s.name, value: s.id })));
    });
  }, []);

  useEffect(() => {
    if (open) {
      const now = dayjs();
      monthRef.current = now;
      setCurrentMonth(now);
      fetchSchedules(now);
      fetchShiftOptions();
    } else {
      setSchedules([]);
    }
  }, [open]);

  const handleShiftChange = (
    scheduleId: number,
    shiftId: number,
    date: Dayjs,
    isNew: boolean,
  ) => {
    if (!isNew) {
      Apis.Attendance.AttendanceSchedules.Update({
        id: scheduleId,
        attendance_shifts_id: shiftId,
      }).then(() => {
        message.success('修改成功');
        reload();
      });
    } else {
      Apis.Attendance.AttendanceSchedules.Store({
        company_employees_id: employeeId!,
        attendance_shifts_id: shiftId,
        asset_projects_id: projectId!,
        organizations_id: organizationId,
        schedule_date: date.format('YYYY-MM-DD') as unknown as Date,
      } as any).then(() => {
        message.success('添加成功');
        reload();
      });
    }
  };

  const handleDelete = (scheduleId: number) => {
    Apis.Attendance.AttendanceSchedules.Cancel({
      id: scheduleId,
    }).then(() => {
      message.success('取消成功');
      reload();
    });
  };

  const dateCellRender = (date: Dayjs) => {
    const matched = schedules.filter((s) =>
      dayjs(s.schedule_date).isSame(date, 'day'),
    );

    const isCancelled = (status?: string) =>
      status === 'Cancelled' || status === 'cancelled';

    return (
      <div>
        {matched.map((s) => (
          <div
            key={s.id}
            style={{
              display: 'flex',
              alignItems: 'center',
              opacity: isCancelled(s.status) ? 0.4 : 1,
              lineHeight: '18px',
            }}
          >
            <Select
              size="small"
              variant="borderless"
              value={s.attendance_shifts_id || s.attendance_shift?.id}
              options={shiftOptions}
              style={{ flex: 1, fontSize: 12 }}
              disabled={isCancelled(s.status)}
              onChange={(val) =>
                val != null && handleShiftChange(s.id, val, date, false)
              }
            />
            {!isCancelled(s.status) && (
              <Popconfirm
                title="是否取消该班次?"
                onConfirm={() => handleDelete(s.id)}
                okText="是"
                cancelText="否"
              >
                <a style={{ fontSize: 12, color: '#ff4d4f', flexShrink: 0 }}>
                  ×
                </a>
              </Popconfirm>
            )}
          </div>
        ))}
        {matched.length === 0 && (
          <Select
            size="small"
            variant="borderless"
            placeholder="+"
            value={undefined}
            options={shiftOptions}
            style={{ width: '100%', fontSize: 12 }}
            onChange={(val) =>
              val != null && handleShiftChange(0, val, date, true)
            }
          />
        )}
      </div>
    );
  };

  return (
    <>
      <MyButtons.Default
        type="link"
        size="small"
        title="查看"
        onClick={() => setOpen(true)}
      />
      <Modal
        title={`${item?.company_employee?.name || ''} - 排班日历`}
        open={open}
        onCancel={() => {
          setOpen(false);
          reloadList?.();
        }}
        footer={null}
        width={1000}
      >
        <Calendar
          value={currentMonth}
          onPanelChange={(date) => {
            monthRef.current = date;
            setCurrentMonth(date);
            fetchSchedules(date);
          }}
          headerRender={() => (
            <div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
              <Select
                options={yearOptions}
                value={currentMonth.year()}
                onChange={(y) => {
                  const next = monthRef.current.year(y);
                  monthRef.current = next;
                  setCurrentMonth(next);
                  fetchSchedules(next);
                }}
              />
              <Select
                options={monthOptions}
                value={currentMonth.month()}
                onChange={(m) => {
                  const next = monthRef.current.month(m);
                  monthRef.current = next;
                  setCurrentMonth(next);
                  fetchSchedules(next);
                }}
              />
            </div>
          )}
          cellRender={(date, info) => {
            if (info.type === 'date') return dateCellRender(date);
            return info.originNode;
          }}
        />
      </Modal>
    </>
  );
}
