import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { FaArrowLeft, FaDownload, FaFileExcel, FaPrint, FaSync, FaTimes } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import * as XLSX from 'xlsx';
import LinkField from './LinkField';
import {
  buildTechnicianWorkSummaryChartData,
  getTechnicianLabel,
  runTechnicianWorkSummaryReport,
  type TechnicianWorkSummaryFilters,
  type TechnicianWorkSummaryRow,
} from '../services/technicianWorkSummaryService';
import { buildMobileTeamSiteFilters, isSiteEnabledHospital } from '../utils/hospitalUtils';
import {
  compactFilterFieldWrapClass,
  compactFilterInputClass,
  compactFilterLabelClass,
  compactSummaryCardClass,
  compactSummaryLabelClass,
  compactSummaryValueClass,
  compactToolbarBtnPrimary,
  compactToolbarBtnSecondary,
} from '../utils/reportModalStyles';

type TechnicianWorkOrderSummaryReportModalProps = {
  isOpen: boolean;
  onClose: () => void;
  permittedIssueTypes?: string[];
  isAdmin?: boolean;
  defaultWorkOrderType?: string;
  defaultFromDate?: string;
  defaultToDate?: string;
  defaultCompany?: string;
  defaultSiteName?: string;
  companyLocked?: boolean;
  siteLocked?: boolean;
  hospitalLinkFilters?: Record<string, unknown>;
};

const TechnicianWorkOrderSummaryReportModal: React.FC<TechnicianWorkOrderSummaryReportModalProps> = ({
  isOpen,
  onClose,
  permittedIssueTypes = [],
  isAdmin = false,
  defaultWorkOrderType = '',
  defaultFromDate = '',
  defaultToDate = '',
  defaultCompany = '',
  defaultSiteName = '',
  companyLocked = false,
  siteLocked = false,
  hospitalLinkFilters,
}) => {
  const { t } = useTranslation();
  const [fromDate, setFromDate] = useState(defaultFromDate);
  const [toDate, setToDate] = useState(defaultToDate);
  const [workOrderType, setWorkOrderType] = useState(defaultWorkOrderType);
  const [company, setCompany] = useState(defaultCompany);
  const [siteName, setSiteName] = useState(defaultSiteName);
  const [rows, setRows] = useState<TechnicianWorkSummaryRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const singlePermittedType = !isAdmin && permittedIssueTypes.length === 1 ? permittedIssueTypes[0] : '';
  const typeLocked = !!singlePermittedType;

  const showSiteFilter = isSiteEnabledHospital(company);
  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(company, siteLocked ? siteName : undefined),
    [company, siteName, siteLocked]
  );

  useEffect(() => {
    if (!isOpen) return;
    setFromDate(defaultFromDate);
    setToDate(defaultToDate);
    setWorkOrderType(singlePermittedType || defaultWorkOrderType);
    setCompany(defaultCompany);
    setSiteName(defaultSiteName);
  }, [
    isOpen,
    defaultFromDate,
    defaultToDate,
    defaultWorkOrderType,
    defaultCompany,
    defaultSiteName,
    singlePermittedType,
  ]);

  useEffect(() => {
    if (!isOpen) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [isOpen, onClose]);

  const buildFilters = useCallback((): TechnicianWorkSummaryFilters => {
    const filters: TechnicianWorkSummaryFilters = {};
    if (fromDate) filters.from_date = fromDate;
    if (toDate) filters.to_date = toDate;
    if (workOrderType) filters.work_order_type = workOrderType;
    if (company) filters.company = company;
    if (siteName && showSiteFilter) filters.site_name = siteName;
    return filters;
  }, [fromDate, toDate, workOrderType, company, siteName, showSiteFilter]);

  const loadReport = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      let result = await runTechnicianWorkSummaryReport(buildFilters());
      setRows(result);
    } catch (err) {
      setRows([]);
      setError(err instanceof Error ? err.message : 'Failed to load report');
    } finally {
      setLoading(false);
    }
  }, [buildFilters]);

  useEffect(() => {
    if (isOpen) {
      loadReport();
    }
  }, [isOpen, loadReport]);

  const summary = useMemo(() => {
    const chart = buildTechnicianWorkSummaryChartData(rows);
    return chart?.totals || { completed: 0, in_progress: 0, open: 0, total: 0 };
  }, [rows]);

  const exportRows = useMemo(
    () =>
      rows.map(row => ({
        Technician: getTechnicianLabel(row),
        Total: Number(row.total) || 0,
        Completed: Number(row.completed) || 0,
        'In Progress': Number(row.in_progress) || 0,
        Open: Number(row.open) || 0,
      })),
    [rows]
  );

  const handleExportCsv = () => {
    if (!exportRows.length) return;
    const headers = Object.keys(exportRows[0]);
    const csv = [
      headers.join(','),
      ...exportRows.map(row => headers.map(h => `"${String((row as any)[h]).replace(/"/g, '""')}"`).join(',')),
    ].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'technician-work-order-summary.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  const handleExportExcel = () => {
    if (!exportRows.length) return;
    const worksheet = XLSX.utils.json_to_sheet(exportRows);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Technicians');
    XLSX.writeFile(workbook, 'technician-work-order-summary.xlsx');
  };

  const handlePrint = () => {
    window.print();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[80] bg-black/50 backdrop-blur-sm">
      <div className="fixed inset-0 bg-white dark:bg-gray-900 flex flex-col print:static print:inset-auto">
        <div className="bg-gradient-to-r from-purple-700 via-indigo-700 to-purple-800 text-white px-4 sm:px-5 py-3 print:bg-white print:text-black">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-2 min-w-0">
              <button
                type="button"
                onClick={onClose}
                className="p-1.5 rounded-lg hover:bg-white/10 print:hidden"
                aria-label="Close"
              >
                <FaArrowLeft className="text-sm" />
              </button>
              <div className="min-w-0">
                <h2 className="text-base sm:text-lg font-semibold truncate">
                  {t('dashboard.techniciansWorked', { defaultValue: 'Technicians Work Summary' })}
                </h2>
                <p className="text-xs sm:text-sm text-purple-100 print:text-gray-600">
                  {t('dashboard.techniciansWorkedReportHint', {
                    defaultValue: 'Work orders grouped by assigned contractor',
                  })}
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-white/10 print:hidden"
              aria-label="Close"
            >
              <FaTimes />
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-3 sm:p-4 space-y-3">
          <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 print:hidden">
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-2">
              <div className={compactFilterFieldWrapClass}>
                <label className={compactFilterLabelClass}>
                  {t('dashboard.fromDate', { defaultValue: 'From Date' })}
                </label>
                <input
                  type="date"
                  value={fromDate}
                  onChange={e => setFromDate(e.target.value)}
                  className={compactFilterInputClass}
                />
              </div>
              <div className={compactFilterFieldWrapClass}>
                <label className={compactFilterLabelClass}>
                  {t('dashboard.toDate', { defaultValue: 'To Date' })}
                </label>
                <input
                  type="date"
                  value={toDate}
                  onChange={e => setToDate(e.target.value)}
                  className={compactFilterInputClass}
                />
              </div>
              <LinkField
                label={t('dashboard.technicalDepartment', { defaultValue: 'Technical Department' })}
                doctype="Issue Type"
                value={workOrderType}
                onChange={setWorkOrderType}
                placeholder={t('dashboard.allDepartments', { defaultValue: 'All Departments' })}
                disabled={typeLocked}
                compact
              />
              <LinkField
                label={t('commonFields.hospital', { defaultValue: 'Hospital' })}
                doctype="Company"
                value={company}
                onChange={value => {
                  setCompany(value);
                  if (!isSiteEnabledHospital(value)) setSiteName('');
                }}
                placeholder={t('dashboard.allHospitals', { defaultValue: 'All Hospitals' })}
                disabled={companyLocked}
                compact
                filters={hospitalLinkFilters}
              />
              {showSiteFilter && (
                <LinkField
                  label={t('commonFields.siteName', { defaultValue: 'PHCC Site' })}
                  doctype="Mobile Team Site"
                  value={siteName}
                  onChange={setSiteName}
                  placeholder={t('dashboard.allSites', { defaultValue: 'All Sites' })}
                  disabled={siteLocked}
                  compact
                  filters={mobileTeamSiteFilters}
                />
              )}
            </div>

            <div className="flex flex-wrap items-center gap-1.5 mt-2">
              <button
                type="button"
                onClick={loadReport}
                disabled={loading}
                className={compactToolbarBtnPrimary('purple')}
              >
                <FaSync className={`text-[10px] ${loading ? 'animate-spin' : ''}`} />
                {t('dashboard.refreshReport', { defaultValue: 'Refresh' })}
              </button>
              <button
                type="button"
                onClick={handleExportCsv}
                disabled={!exportRows.length}
                className={compactToolbarBtnSecondary}
              >
                <FaDownload className="text-[10px]" />
                CSV
              </button>
              <button
                type="button"
                onClick={handleExportExcel}
                disabled={!exportRows.length}
                className={compactToolbarBtnSecondary}
              >
                <FaFileExcel className="text-[10px]" />
                Excel
              </button>
              <button
                type="button"
                onClick={handlePrint}
                disabled={!exportRows.length}
                className={compactToolbarBtnSecondary}
              >
                <FaPrint className="text-[10px]" />
                {t('listPages.print', { defaultValue: 'Print' })}
              </button>
            </div>
          </div>

          <div className="grid grid-cols-2 lg:grid-cols-4 gap-2">
            <SummaryStat label={t('dashboard.totalWorkOrders', { defaultValue: 'Total' })} value={summary.total} />
            <SummaryStat label={t('dashboard.completedWorkOrders', { defaultValue: 'Completed' })} value={summary.completed} color="text-green-600" />
            <SummaryStat label={t('dashboard.workOrdersInProgress', { defaultValue: 'In Progress' })} value={summary.in_progress} color="text-blue-600" />
            <SummaryStat label={t('dashboard.openWorkOrders', { defaultValue: 'Open' })} value={summary.open} color="text-amber-600" />
          </div>

          {error && (
            <div className="rounded-md border border-red-200 bg-red-50 text-red-700 px-4 py-3 text-sm">
              {error}
            </div>
          )}

          <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead className="bg-gray-50 dark:bg-gray-900/60">
                  <tr>
                    <th className="px-4 py-3 text-left font-semibold text-gray-700 dark:text-gray-200">
                      {t('commonFields.assignedContractor', { defaultValue: 'Assigned Contractor' })}
                    </th>
                    <th className="px-4 py-3 text-right font-semibold text-gray-700 dark:text-gray-200">Total</th>
                    <th className="px-4 py-3 text-right font-semibold text-green-700 dark:text-green-400">Completed</th>
                    <th className="px-4 py-3 text-right font-semibold text-blue-700 dark:text-blue-400">In Progress</th>
                    <th className="px-4 py-3 text-right font-semibold text-amber-700 dark:text-amber-400">Open</th>
                  </tr>
                </thead>
                <tbody>
                  {loading ? (
                    <tr>
                      <td colSpan={5} className="px-4 py-10 text-center text-gray-500">
                        {t('common.loading', { defaultValue: 'Loading...' })}
                      </td>
                    </tr>
                  ) : rows.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="px-4 py-10 text-center text-gray-500">
                        {t('common.noData', { defaultValue: 'No data' })}
                      </td>
                    </tr>
                  ) : (
                    rows.map((row, index) => (
                      <tr key={`${getTechnicianLabel(row)}-${index}`} className="border-t border-gray-100 dark:border-gray-700">
                        <td className="px-4 py-3 text-gray-800 dark:text-gray-100">{getTechnicianLabel(row)}</td>
                        <td className="px-4 py-3 text-right font-medium">{Number(row.total) || 0}</td>
                        <td className="px-4 py-3 text-right text-green-700 dark:text-green-400">{Number(row.completed) || 0}</td>
                        <td className="px-4 py-3 text-right text-blue-700 dark:text-blue-400">{Number(row.in_progress) || 0}</td>
                        <td className="px-4 py-3 text-right text-amber-700 dark:text-amber-400">{Number(row.open) || 0}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const SummaryStat: React.FC<{ label: string; value: number; color?: string }> = ({
  label,
  value,
  color = 'text-gray-900 dark:text-white',
}) => (
  <div className={`${compactSummaryCardClass} border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800`}>
    <div className={compactSummaryLabelClass}>{label}</div>
    <div className={`${compactSummaryValueClass} mt-0.5 ${color}`}>{value}</div>
  </div>
);

export default TechnicianWorkOrderSummaryReportModal;
