import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Button, Input, Table, Tag, Space, Tooltip, message } from 'antd';
import { SearchOutlined, CheckOutlined, ReloadOutlined, SaveOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import type { AttendanceStatusType, DailyAttendanceItem } from '../types';

interface MarkAttendanceModalProps {
  open: boolean;
  onCancel: () => void;
  selectedDate: Dayjs;
  attendanceItems: DailyAttendanceItem[];
  loading: boolean;
  saving: boolean;
  onSaveAttendance: (draftItems: DailyAttendanceItem[]) => Promise<void> | void;
}

export const MarkAttendanceModal: React.FC<MarkAttendanceModalProps> = ({
  open,
  onCancel,
  selectedDate,
  attendanceItems,
  loading,
  saving,
  onSaveAttendance,
}) => {
  // Local draft state for marking attendance inside the modal
  const [draftItems, setDraftItems] = useState<DailyAttendanceItem[]>([]);
  const [modalSearchText, setModalSearchText] = useState<string>('');

  // Sync draft state from saved attendanceItems whenever modal is opened
  useEffect(() => {
    if (open) {
      setDraftItems(attendanceItems.map((item) => ({ ...item })));
      setModalSearchText('');
    }
  }, [open, attendanceItems]);

  // Local status change handler
  const handleStatusChange = (employeeId: string, newStatus: AttendanceStatusType) => {
    setDraftItems((prev) =>
      prev.map((item) => (item.employeeId === employeeId ? { ...item, status: newStatus } : item))
    );
  };

  // Local remarks change handler
  const handleRemarksChange = (employeeId: string, remarks: string) => {
    setDraftItems((prev) =>
      prev.map((item) => (item.employeeId === employeeId ? { ...item, remarks } : item))
    );
  };

  // Quick Action: Mark all draft employees as Present
  const handleSelectAllPresent = () => {
    setDraftItems((prev) =>
      prev.map((item) => ({ ...item, status: 'PRESENT' as const }))
    );
    message.success('All employees marked as Present (P)');
  };

  // Reset draft to initial saved state
  const handleReset = () => {
    setDraftItems(attendanceItems.map((item) => ({ ...item })));
  };

  // Filter draft items inside modal by employee name or designation
  const filteredDraftItems = useMemo(() => {
    if (!modalSearchText.trim()) return draftItems;
    const q = modalSearchText.toLowerCase().trim();
    return draftItems.filter(
      (item) =>
        item.name.toLowerCase().includes(q) ||
        (item.designation && item.designation.toLowerCase().includes(q))
    );
  }, [draftItems, modalSearchText]);

  // Interactive Status Radio Tick Buttons inside Mark Modal
  const renderRadioTickButtons = (record: DailyAttendanceItem) => {
    const options: { label: string; short: string; value: AttendanceStatusType; activeColor: string; title: string }[] = [
      { label: 'Present', short: 'P', value: 'PRESENT', activeColor: 'bg-emerald-600 border-emerald-600 text-white', title: 'Present' },
      { label: 'Absent', short: 'A', value: 'ABSENT', activeColor: 'bg-rose-600 border-rose-600 text-white', title: 'Absent' },
      { label: 'Half Day', short: 'H', value: 'HALF_DAY', activeColor: 'bg-amber-500 border-amber-500 text-white', title: 'Half Day' },
    ];

    return (
      <div className="flex items-center gap-4">
        {options.map((opt) => {
          const isChecked = record.status === opt.value;
          return (
            <Tooltip title={opt.title} key={opt.value}>
              <label
                onClick={() => handleStatusChange(record.employeeId, opt.value)}
                className="inline-flex items-center gap-1.5 cursor-pointer text-xs font-semibold select-none transition-all hover:opacity-80"
              >
                <span
                  className={`w-4 h-4 rounded-full border flex items-center justify-center transition-all ${
                    isChecked
                      ? opt.activeColor
                      : 'border-slate-300 bg-white hover:border-slate-400'
                  }`}
                >
                  {isChecked && <CheckOutlined className="text-[9px] stroke-3" />}
                </span>
                <span className={isChecked ? 'text-slate-900 font-bold' : 'text-slate-600 font-medium'}>
                  {opt.label}
                </span>
              </label>
            </Tooltip>
          );
        })}
      </div>
    );
  };

  return (
    <Modal
      title={
        <div className="flex items-center justify-between pr-6 py-1 border-b border-slate-200">
          <span className="text-lg font-bold text-slate-900">Attendance</span>
          <Tag color="blue" className="font-mono font-bold text-sm px-3 py-0.5 rounded-md">
            Attendance - {selectedDate.format('DD MMM YYYY')}
          </Tag>
        </div>
      }
      open={open}
      onCancel={onCancel}
      width={920}
      footer={[
        <Button key="close" onClick={onCancel} className="rounded-lg">
          Cancel
        </Button>,
        <Button
          key="save"
          type="primary"
          icon={<SaveOutlined />}
          loading={saving}
          onClick={() => onSaveAttendance(draftItems)}
          className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg px-5"
        >
          Save Attendance
        </Button>,
      ]}
    >
      <div className="py-3 space-y-4">
        {/* Header Controls inside Modal */}
        <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 flex flex-wrap items-center justify-between gap-4">
          <Input
            placeholder="Search Employee..."
            prefix={<SearchOutlined className="text-slate-400" />}
            value={modalSearchText}
            onChange={(e) => setModalSearchText(e.target.value)}
            allowClear
            className="w-64 rounded-lg h-9 text-xs"
          />
          <span className="font-bold text-slate-700 text-xs">
            Total : <span className="text-blue-600 font-extrabold">{draftItems.length}</span> Employees
          </span>
          <Space wrap>
            <Button
              size="small"
              icon={<CheckOutlined />}
              onClick={handleSelectAllPresent}
              className="rounded-md font-semibold text-xs h-8"
            >
              Select All Present
            </Button>
            <Button
              size="small"
              icon={<ReloadOutlined />}
              onClick={handleReset}
              className="rounded-md font-semibold text-xs h-8"
            >
              Reset
            </Button>
          </Space>
        </div>

        {/* Interactive Scrollable Minimized Spreadsheet Grid Table */}
        <div className="border border-slate-300 rounded-lg overflow-hidden shadow-2xs">
          <Table
            rowKey="employeeId"
            loading={loading}
            dataSource={filteredDraftItems}
            bordered={false}
            columns={[
              {
                title: 'Employee Name',
                dataIndex: 'name',
                key: 'name',
                width: 180,
                render: (n: string) => <span className="font-bold text-slate-900 text-xs">{n}</span>,
              },
              {
                title: 'Designation',
                dataIndex: 'designation',
                key: 'designation',
                width: 150,
                render: (d: string) => <span className="text-xs text-slate-600 font-medium">{d || 'Staff'}</span>,
              },
              {
                title: 'Attendance',
                key: 'status',
                width: 300,
                render: (_: any, record: DailyAttendanceItem) => renderRadioTickButtons(record),
              },
              {
                title: 'Remarks',
                dataIndex: 'remarks',
                key: 'remarks',
                render: (remarks: string, record: DailyAttendanceItem) => (
                  <Input
                    placeholder="Enter remarks..."
                    value={remarks || ''}
                    onChange={(e) => handleRemarksChange(record.employeeId, e.target.value)}
                    className="rounded text-xs border-slate-300 h-7"
                  />
                ),
              },
            ]}
            pagination={false}
            scroll={{ y: 380 }}
            size="small"
            className="attendance-grid-table"
          />
        </div>
      </div>
    </Modal>
  );
};

export default MarkAttendanceModal;
