import React from 'react';
import { Modal, Button, Spin, Row, Col, Calendar, Select, Tooltip } from 'antd';
import { CalendarOutlined } from '@ant-design/icons';
import dayjs, { type Dayjs } from 'dayjs';
import type { SingleEmployeeSummary } from '../types';

interface SingleEmployeeMatrixModalProps {
  open: boolean;
  onCancel: () => void;
  singleEmployeeName: string;
  singleEmployeeData: SingleEmployeeSummary | null;
  singleMatrixLoading: boolean;
  singleMatrixMonth: Dayjs;
  onMonthChange: (newMonth: Dayjs) => void;
}

export const SingleEmployeeMatrixModal: React.FC<SingleEmployeeMatrixModalProps> = ({
  open,
  onCancel,
  singleEmployeeName,
  singleEmployeeData,
  singleMatrixLoading,
  singleMatrixMonth,
  onMonthChange,
}) => {
  const todayYear = dayjs().year();
  const todayMonth = dayjs().month();

  return (
    <Modal
      title={
        <div className="flex items-center justify-between pr-6 py-1 border-b border-slate-200">
          <div className="flex items-center gap-2">
            <CalendarOutlined className="text-purple-600 text-lg" />
            <span className="text-lg font-bold text-slate-900">
              Single Employee Matrix: {singleEmployeeName}
            </span>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 text-xs">
              <span className="inline-flex items-center gap-1 font-bold text-emerald-700">
                <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block" /> Present (P)
              </span>
              <span className="inline-flex items-center gap-1 font-bold text-rose-700">
                <span className="w-2.5 h-2.5 rounded-full bg-rose-500 inline-block" /> Absent (A)
              </span>
              <span className="inline-flex items-center gap-1 font-bold text-amber-700">
                <span className="w-2.5 h-2.5 rounded-full bg-amber-500 inline-block" /> Half Day (H)
              </span>
            </div>
          </div>
        </div>
      }
      open={open}
      onCancel={onCancel}
      width={700}
      footer={[
        <Button key="close" onClick={onCancel} className="rounded-lg">
          Close
        </Button>,
      ]}
    >
      <Spin spinning={singleMatrixLoading}>
        <div className="py-3 space-y-4">
          {singleEmployeeData && (
            <>
              {/* Employee Stats Summary */}
              <Row gutter={[12, 12]}>
                <Col span={6}>
                  <div className="bg-slate-50 border border-slate-200 rounded-xl p-3 text-center">
                    <div className="text-xs text-slate-500 font-bold uppercase">Recorded Days</div>
                    <div className="text-xl font-extrabold text-slate-900 mt-1">
                      {singleEmployeeData.stats.totalDays}
                    </div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-3 text-center">
                    <div className="text-xs text-emerald-700 font-bold uppercase">Present (P)</div>
                    <div className="text-xl font-extrabold text-emerald-700 mt-1">
                      {singleEmployeeData.stats.presentDays}
                    </div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="bg-rose-50 border border-rose-200 rounded-xl p-3 text-center">
                    <div className="text-xs text-rose-700 font-bold uppercase">Absent (A)</div>
                    <div className="text-xl font-extrabold text-rose-700 mt-1">
                      {singleEmployeeData.stats.absentDays}
                    </div>
                  </div>
                </Col>
                <Col span={6}>
                  <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 text-center">
                    <div className="text-xs text-amber-700 font-bold uppercase">Half Day (H)</div>
                    <div className="text-xl font-extrabold text-amber-700 mt-1">
                      {singleEmployeeData.stats.halfDays}
                    </div>
                  </div>
                </Col>
              </Row>

              {/* Calendar with Month Selector Only */}
              <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs">
                <Calendar
                  fullscreen={false}
                  value={singleMatrixMonth}
                  headerRender={({ value, onChange }) => {
                    const monthOptions = [];
                    for (let i = 0; i < 12; i++) {
                      const isFutureMonth = value.year() === todayYear && i > todayMonth;
                      monthOptions.push(
                        <Select.Option key={i} value={i} disabled={isFutureMonth}>
                          {dayjs().month(i).format('MMMM')}
                        </Select.Option>
                      );
                    }
                    const currentMonth = value.month();

                    return (
                      <div className="flex items-center justify-between p-2 mb-2 border-b border-slate-100">
                        <span className="font-bold text-sm text-slate-800">
                          {value.format('MMMM YYYY')}
                        </span>
                        <Select
                          size="small"
                          value={currentMonth}
                          onChange={(newMonth) => {
                            if (value.year() === todayYear && newMonth > todayMonth) {
                              return;
                            }
                            const updated = value.clone().month(newMonth);
                            onChange(updated);
                            onMonthChange(updated);
                          }}
                          className="w-36 font-semibold"
                        >
                          {monthOptions}
                        </Select>
                      </div>
                    );
                  }}
                  disabledDate={(current) => current ? current.isAfter(dayjs().endOf('day')) : false}
                  cellRender={(current, info) => {
                    if (info.type !== 'date') return null;
                    const dateStr = current.format('YYYY-MM-DD');
                    const log = singleEmployeeData.recentLogs.find((l) => l.date === dateStr);
                    if (!log) return null;

                    let dotClass = 'bg-emerald-500';
                    let statusText = 'Present (P)';
                    if (log.status === 'ABSENT') {
                      dotClass = 'bg-rose-500';
                      statusText = 'Absent (A)';
                    } else if (log.status === 'HALF_DAY') {
                      dotClass = 'bg-amber-500';
                      statusText = 'Half Day (H)';
                    }

                    return (
                      <Tooltip title={`${log.date}: ${statusText}${log.remarks ? ` (${log.remarks})` : ''}`}>
                        <div className="flex items-center justify-center mt-1">
                          <span className={`w-2.5 h-2.5 rounded-full ${dotClass} shadow-2xs inline-block`} />
                        </div>
                      </Tooltip>
                    );
                  }}
                />
              </div>
            </>
          )}
        </div>
      </Spin>
    </Modal>
  );
};
