import React from 'react';
import { Modal, Button, Spin, Tag, Tooltip, DatePicker, Input } from 'antd';
import { ReloadOutlined, LeftOutlined, RightOutlined, SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import type { MonthlyEmployee } from '../types';

interface MonthlyMatrixModalProps {
  open: boolean;
  onCancel: () => void;
  calendarMonth: Dayjs;
  monthlyData: MonthlyEmployee[];
  monthlyLoading: boolean;
  searchText?: string;
  onSearchChange?: (val: string) => void;
  onFetchMonthlyAttendance: () => void;
  onMonthChange: (newMonth: Dayjs) => void;
}

export const MonthlyMatrixModal: React.FC<MonthlyMatrixModalProps> = ({
  open,
  onCancel,
  calendarMonth,
  monthlyData,
  monthlyLoading,
  searchText = '',
  onSearchChange,
  onFetchMonthlyAttendance,
  onMonthChange,
}) => {
  const disableFutureMonth = (current: Dayjs) => current.isAfter(dayjs().endOf('month'));

  return (
    <Modal
      title={
        <div className="flex items-center justify-between pr-6 py-1 border-b border-slate-200 flex-wrap gap-2">
          <div className="flex items-center gap-3">
            <span className="text-lg font-bold text-slate-900">Monthly Attendance Matrix View</span>
            <Tag color="blue" className="font-bold rounded-md px-2 py-0.5">
              {monthlyData.length} Employees
            </Tag>
          </div>
          
          <div className="flex items-center gap-2">
            <Button
              size="small"
              icon={<LeftOutlined />}
              onClick={() => onMonthChange(calendarMonth.subtract(1, 'month'))}
              title="Previous Month"
              className="rounded-md"
            />
            <DatePicker
              picker="month"
              format="MMMM YYYY"
              value={calendarMonth}
              onChange={(d) => d && onMonthChange(d)}
              disabledDate={disableFutureMonth}
              allowClear={false}
              className="font-bold text-sm rounded-md"
              style={{ width: 160 }}
            />
            <Button
              size="small"
              icon={<RightOutlined />}
              onClick={() => {
                const nextMonth = calendarMonth.add(1, 'month');
                if (!nextMonth.isAfter(dayjs(), 'month')) {
                  onMonthChange(nextMonth);
                }
              }}
              title="Next Month"
              className="rounded-md"
            />
          </div>
        </div>
      }
      open={open}
      onCancel={onCancel}
      width={1150}
      footer={[
        <Button key="close" onClick={onCancel} className="rounded-lg font-medium">
          Close
        </Button>,
      ]}
    >
      <div className="py-3 space-y-3">
        <div className="flex items-center justify-between flex-wrap gap-2">
          <div className="flex items-center gap-2">
            <span className="bg-emerald-100 text-emerald-800 px-2.5 py-1 rounded-md text-xs font-bold">
              P = Present
            </span>
            <span className="bg-rose-100 text-rose-800 px-2.5 py-1 rounded-md text-xs font-bold">
              A = Absent
            </span>
            <span className="bg-amber-100 text-amber-800 px-2.5 py-1 rounded-md text-xs font-bold">
              H = Half Day
            </span>
          </div>
          <div className="flex items-center gap-2">
            <Input
              placeholder="Search employee..."
              prefix={<SearchOutlined className="text-gray-400" />}
              value={searchText}
              onChange={(e) => onSearchChange?.(e.target.value)}
              allowClear
              size="small"
              style={{ width: 220 }}
            />
            <Button
              size="small"
              icon={<ReloadOutlined spin={monthlyLoading} />}
              onClick={onFetchMonthlyAttendance}
              className="rounded-md font-semibold text-xs"
            >
              Refresh Matrix
            </Button>
          </div>
        </div>

        <Spin spinning={monthlyLoading}>
          <div className="overflow-auto border border-slate-200 rounded-xl shadow-2xs max-h-[60vh] relative">
            <table className="w-full text-center text-xs border-collapse bg-white">
              <thead>
                <tr className="bg-slate-100 border-b border-slate-200 text-slate-700 font-bold sticky top-0 z-30">
                  <th className="sticky left-0 bg-slate-100 z-40 text-left px-3.5 py-3 min-w-40 border-r border-slate-200 shadow-xs">
                    Employee Name
                  </th>
                  <th className="px-2.5 py-3 min-w-25 bg-slate-100">Designation</th>
                  {Array.from({ length: calendarMonth.daysInMonth() }, (_, i) => i + 1).map((day) => (
                    <th key={day} className="px-1 py-2 min-w-8 border-l border-slate-200 bg-slate-100">
                      {day}
                    </th>
                  ))}
                  <th className="px-2.5 py-3 border-l-2 border-slate-300 text-emerald-700 bg-slate-100">P</th>
                  <th className="px-2.5 py-3 text-rose-700 bg-slate-100">A</th>
                  <th className="px-2.5 py-3 text-amber-700 bg-slate-100">H</th>
                  <th className="px-2.5 py-3 bg-slate-100">Rate</th>
                </tr>
              </thead>
              <tbody>
                {monthlyData.map((emp, idx) => (
                  <tr
                    key={emp.employeeId}
                    className={`border-b border-slate-100 transition-colors ${idx % 2 === 1 ? 'bg-slate-50/50 hover:bg-slate-100/70' : 'bg-white hover:bg-slate-50'}`}
                  >
                    <td className={`sticky left-0 z-20 text-left px-3.5 py-2.5 font-bold text-slate-800 border-r border-slate-200 shadow-xs ${idx % 2 === 1 ? 'bg-slate-50' : 'bg-white'}`}>
                      {emp.name}
                    </td>
                    <td className="px-2 py-2 text-xs text-slate-600">
                      {emp.designation || 'Staff'}
                    </td>

                    {Array.from({ length: calendarMonth.daysInMonth() }, (_, i) => i + 1).map((day) => {
                      const rec = emp.daily[day];
                      const st = rec?.status;
                      let bgClass = 'bg-slate-100 text-slate-400';
                      let code = '-';

                      if (st === 'PRESENT') {
                        bgClass = 'bg-emerald-100 text-emerald-800';
                        code = 'P';
                      } else if (st === 'ABSENT') {
                        bgClass = 'bg-rose-100 text-rose-800';
                        code = 'A';
                      } else if (st === 'HALF_DAY') {
                        bgClass = 'bg-amber-100 text-amber-800';
                        code = 'H';
                      }

                      return (
                        <td key={day} className="p-1 border-l border-slate-100">
                          <Tooltip title={`${emp.name} (${day} ${calendarMonth.format('MMM')}): ${st || 'Not Marked'}`}>
                            <div className={`font-black rounded-md py-0.5 text-xs ${bgClass}`}>
                              {code}
                            </div>
                          </Tooltip>
                        </td>
                      );
                    })}

                    <td className="px-2 py-2 font-black text-emerald-700 border-l-2 border-slate-200">
                      {emp.stats.presentDays}
                    </td>
                    <td className="px-2 py-2 font-black text-rose-700">
                      {emp.stats.absentDays}
                    </td>
                    <td className="px-2 py-2 font-black text-amber-700">
                      {emp.stats.halfDays}
                    </td>
                    <td className="px-2 py-2">
                      <Tag color={emp.stats.attendanceRate >= 80 ? 'success' : 'warning'} className="rounded-md font-bold">
                        {emp.stats.attendanceRate}%
                      </Tag>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Spin>
      </div>
    </Modal>
  );
};
