import React, { useEffect, useState } from 'react';
import { Modal, Button, Select, DatePicker, message, Row, Col } from 'antd';
import { DownloadOutlined, FilePdfOutlined, FileExcelOutlined } from '@ant-design/icons';
import dayjs, { type Dayjs } from 'dayjs';
import type { AttendanceExportConfig } from '../types';

interface ExportAttendanceModalProps {
  open: boolean;
  onCancel: () => void;
  onExport: (config: AttendanceExportConfig) => void;
  employees?: Array<{ id: string | number; name: string; employeeCode?: string }>;
  exportLoading?: boolean;
}

export const ExportAttendanceModal: React.FC<ExportAttendanceModalProps> = ({
  open,
  onCancel,
  onExport,
  employees = [],
  exportLoading = false,
}) => {
  const [fromDate, setFromDate] = useState<Dayjs>(dayjs().startOf('month'));
  const [toDate, setToDate] = useState<Dayjs>(dayjs());
  const [selectedEmployeeId, setSelectedEmployeeId] = useState<string | number | undefined>(undefined);

  useEffect(() => {
    if (!open) {
      setFromDate(dayjs().startOf('month'));
      setToDate(dayjs());
      setSelectedEmployeeId(undefined);
    }
  }, [open]);

  const disableFutureDate = (current: Dayjs) => current.isAfter(dayjs().endOf('day'));

  const handleTriggerExport = (format: 'pdf' | 'excel') => {
    if (!fromDate || !toDate) {
      message.error('Please select both From Date and To Date.');
      return;
    }
    if (fromDate.isAfter(toDate)) {
      message.error('From Date cannot be after To Date.');
      return;
    }

    const config: AttendanceExportConfig = {
      reportType: 'EMPLOYEE',
      format,
      fromDate: fromDate.format('YYYY-MM-DD'),
      toDate: toDate.format('YYYY-MM-DD'),
      employeeId: selectedEmployeeId,
    };

    onExport(config);
  };

  return (
    <Modal
      title={
        <div className="flex items-center gap-2 py-2 border-b border-slate-200">
          <DownloadOutlined className="text-emerald-600 text-xl" />
          <div>
            <h3 className="text-lg font-bold text-slate-900 m-0">Export Attendance Reports</h3>
            <p className="text-xs text-slate-500 font-normal m-0">Select date range, apply optional filters, and choose export format</p>
          </div>
        </div>
      }
      open={open}
      onCancel={onCancel}
      width={680}
      footer={null}
      destroyOnHidden
    >
      <div className="py-4 space-y-6">
        <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 space-y-4">
          <div className="text-xs font-bold text-slate-600 uppercase tracking-wider">
            Report Filters
          </div>

          <Row gutter={[16, 16]}>
            <Col xs={24} md={12}>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                From Date <span className="text-rose-500">*</span>
              </label>
              <DatePicker
                value={fromDate}
                onChange={(d) => d && setFromDate(d)}
                format="DD-MM-YYYY"
                disabledDate={disableFutureDate}
                className="w-full rounded-lg"
              />
            </Col>
            <Col xs={24} md={12}>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                To Date <span className="text-rose-500">*</span>
              </label>
              <DatePicker
                value={toDate}
                onChange={(d) => d && setToDate(d)}
                format="DD-MM-YYYY"
                disabledDate={disableFutureDate}
                className="w-full rounded-lg"
              />
            </Col>

            <Col xs={24} md={24}>
              <label className="block text-xs font-semibold text-slate-700 mb-1">
                Employee (Optional)
              </label>
              <Select
                allowClear
                showSearch
                placeholder="All Employees"
                value={selectedEmployeeId}
                onChange={setSelectedEmployeeId}
                filterOption={(input, option) =>
                  (option?.children as unknown as string)
                    ?.toLowerCase()
                    ?.includes(input.toLowerCase())
                }
                className="w-full"
              >
                {employees.map((emp) => (
                  <Select.Option key={emp.id} value={emp.id}>
                    {emp.employeeCode ? `[${emp.employeeCode}] ${emp.name}` : emp.name}
                  </Select.Option>
                ))}
              </Select>
            </Col>
          </Row>
        </div>

        {/* Export Actions */}
        <div className="flex items-center justify-end gap-3 pt-2 border-t border-slate-200">
          <Button onClick={onCancel} className="rounded-xl font-medium">
            Cancel
          </Button>
          <Button
            type="primary"
            danger
            icon={<FilePdfOutlined />}
            loading={exportLoading}
            onClick={() => handleTriggerExport('pdf')}
            className="rounded-xl font-bold px-5"
          >
            Export PDF
          </Button>
          <Button
            icon={<FileExcelOutlined className="text-emerald-600" />}
            loading={exportLoading}
            onClick={() => handleTriggerExport('excel')}
            className="rounded-xl font-bold px-5 border-emerald-600 text-emerald-600 hover:bg-emerald-50 hover:border-emerald-700"
          >
            Export Excel
          </Button>
        </div>
      </div>
    </Modal>
  );
};

