import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  FaArrowLeft,
  FaClock,
  FaDownload,
  FaFileExcel,
  FaFilter,
  FaPrint,
  FaSync,
  FaTimes,
  FaUserCog,
  FaUsers,
} from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import * as XLSX from 'xlsx';
import LinkField from './LinkField';
import {
  getTechnicianHoursLabel,
  parseTechnicianHours,
  runTechnicianWorkingHoursReport,
  type TechnicianWorkingHoursFilters,
  type TechnicianWorkingHoursRow,
} from '../services/technicianWorkingHoursService';
import { buildMobileTeamSiteFilters, isSiteEnabledHospital } from '../utils/hospitalUtils';
import {
  compactFilterFieldWrapClass,
  compactFilterInputClass,
  compactFilterLabelClass,
  compactSummaryCardClass,
  compactSummaryLabelClass,
  compactSummaryValueClass,
  compactToolbarBtnPrimary,
  compactToolbarBtnSecondary,
} from '../utils/reportModalStyles';

type TechnicianWorkingHoursReportModalProps = {
  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 TechnicianWorkingHoursReportModal: React.FC<TechnicianWorkingHoursReportModalProps> = ({
  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<TechnicianWorkingHoursRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filtersExpanded, setFiltersExpanded] = useState(true);

  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);
    setFiltersExpanded(true);
  }, [
    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 activeFilterCount = useMemo(() => {
    let count = 0;
    if (fromDate) count += 1;
    if (toDate) count += 1;
    if (workOrderType) count += 1;
    if (company) count += 1;
    if (siteName && showSiteFilter) count += 1;
    return count;
  }, [fromDate, toDate, workOrderType, company, siteName, showSiteFilter]);

  const buildFilters = useCallback((): TechnicianWorkingHoursFilters => {
    const filters: TechnicianWorkingHoursFilters = {};
    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 {
      const result = await runTechnicianWorkingHoursReport(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 totalTechnicians = rows.length;
    const totalHours = rows.reduce((sum, row) => sum + parseTechnicianHours(row.total_hours), 0);
    const avgHours = totalTechnicians > 0 ? totalHours / totalTechnicians : 0;
    return {
      totalTechnicians,
      totalHours: Math.round(totalHours * 100) / 100,
      avgHours: Math.round(avgHours * 100) / 100,
    };
  }, [rows]);

  const exportRows = useMemo(
    () =>
      rows.map(row => ({
        Engineer: row.engineer || '',
        'Technician Name': getTechnicianHoursLabel(row),
        'Total Hours': parseTechnicianHours(row.total_hours),
      })),
    [rows]
  );

  const handleClearFilters = () => {
    setFromDate(defaultFromDate);
    setToDate(defaultToDate);
    setWorkOrderType(singlePermittedType || defaultWorkOrderType);
    setCompany(defaultCompany);
    setSiteName(defaultSiteName);
  };

  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 = 'technicians-working-hours.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, 'technicians-working-hours.xlsx');
  };

  const handlePrint = () => {
    if (!exportRows.length) return;

    const tableRows = rows
      .map(
        (row, index) => `
          <tr>
            <td>${index + 1}</td>
            <td>${getTechnicianHoursLabel(row)}</td>
            <td>${row.engineer || ''}</td>
            <td class="hours">${parseTechnicianHours(row.total_hours)} hrs</td>
          </tr>
        `
      )
      .join('');

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Technicians Working Hours</title>
          <style>
            body { font-family: Arial, sans-serif; padding: 24px; color: #111827; }
            h1 { color: #0891B2; margin-bottom: 8px; }
            p { color: #6B7280; margin-top: 0; }
            table { width: 100%; border-collapse: collapse; margin-top: 20px; }
            th { background: #0891B2; color: white; text-align: left; padding: 10px 12px; }
            td { border-bottom: 1px solid #E5E7EB; padding: 10px 12px; }
            .hours { color: #0891B2; font-weight: 700; }
          </style>
        </head>
        <body>
          <h1>Technicians Working Hours</h1>
          <p>${rows.length} technicians • ${summary.totalHours} total hours</p>
          <table>
            <thead>
              <tr>
                <th>#</th>
                <th>Technician Name</th>
                <th>Engineer</th>
                <th>Total Hours</th>
              </tr>
            </thead>
            <tbody>${tableRows}</tbody>
          </table>
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.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">
        <div className="bg-gradient-to-r from-cyan-600 to-blue-600 text-white px-4 sm:px-5 py-3">
          <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"
                aria-label="Back"
              >
                <FaArrowLeft className="text-sm" />
              </button>
              <div className="w-8 h-8 rounded-full bg-white/15 flex items-center justify-center shrink-0">
                <FaClock className="text-sm" />
              </div>
              <div className="min-w-0">
                <h2 className="text-base sm:text-lg font-semibold truncate">
                  {t('dashboard.technicianWorkingHours', { defaultValue: 'Technicians Working Hours' })}
                </h2>
                <p className="text-xs sm:text-sm text-cyan-100">
                  {t('dashboard.technicianHoursFound', {
                    count: summary.totalTechnicians,
                    defaultValue: `${summary.totalTechnicians} technicians found`,
                  })}
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-white/10"
              aria-label="Close"
            >
              <FaTimes />
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-3 sm:p-4 space-y-3">
          {!loading && rows.length > 0 && (
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
              <SummaryCard
                icon={<FaUsers className="text-blue-500" />}
                label={t('dashboard.totalTechnicians', { defaultValue: 'Total Technicians' })}
                value={String(summary.totalTechnicians)}
                theme="blue"
              />
              <SummaryCard
                icon={<FaClock className="text-cyan-500" />}
                label={t('dashboard.totalHoursWorked', { defaultValue: 'Total Hours Worked' })}
                value={`${summary.totalHours} hrs`}
                theme="cyan"
              />
              <SummaryCard
                icon={<FaUserCog className="text-purple-500" />}
                label={t('dashboard.avgHoursPerTechnician', { defaultValue: 'Average Hours/Technician' })}
                value={`${summary.avgHours} hrs`}
                theme="purple"
              />
            </div>
          )}

          <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
            <div className="flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-b border-gray-200 dark:border-gray-700">
              <button
                type="button"
                onClick={() => setFiltersExpanded(prev => !prev)}
                className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-200"
              >
                <FaFilter className="text-cyan-600 text-xs" />
                {t('dashboard.filters', { defaultValue: 'Filters' })}
                {activeFilterCount > 0 && (
                  <span className="inline-flex items-center justify-center min-w-[1rem] h-4 px-1 rounded-full bg-cyan-100 text-cyan-700 text-[10px] font-semibold">
                    {activeFilterCount}
                  </span>
                )}
              </button>

              <div className="flex flex-wrap items-center gap-1.5">
                <button
                  type="button"
                  onClick={loadReport}
                  disabled={loading}
                  className={compactToolbarBtnPrimary('cyan')}
                >
                  <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]" />
                  PDF/Print
                </button>
              </div>
            </div>

            {filtersExpanded && (
              <div className="p-3 border-b border-gray-200 dark:border-gray-700">
                <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="mt-2">
                  <button
                    type="button"
                    onClick={handleClearFilters}
                    className="text-[11px] text-cyan-700 dark:text-cyan-300 hover:underline"
                  >
                    {t('dashboard.clearFilters', { defaultValue: 'Clear Filters' })}
                  </button>
                </div>
              </div>
            )}
          </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 sticky top-0 z-10">
                  <tr>
                    <th className="px-4 py-3 text-left font-semibold text-gray-700 dark:text-gray-200 w-12">#</th>
                    <th className="px-4 py-3 text-left font-semibold text-gray-700 dark:text-gray-200">
                      {t('dashboard.technicianName', { defaultValue: 'Technician Name' })}
                    </th>
                    <th className="px-4 py-3 text-left font-semibold text-gray-700 dark:text-gray-200">
                      {t('dashboard.engineer', { defaultValue: 'Engineer' })}
                    </th>
                    <th className="px-4 py-3 text-right font-semibold text-gray-700 dark:text-gray-200">
                      {t('dashboard.totalHoursSpent', { defaultValue: 'Total Hours Spent' })}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {loading ? (
                    <tr>
                      <td colSpan={4} className="px-4 py-10 text-center text-gray-500">
                        {t('dashboard.loadingTechnicianHours', { defaultValue: 'Loading technician hours…' })}
                      </td>
                    </tr>
                  ) : rows.length === 0 ? (
                    <tr>
                      <td colSpan={4} className="px-4 py-10 text-center text-gray-500">
                        {t('common.noData', { defaultValue: 'No data' })}
                      </td>
                    </tr>
                  ) : (
                    rows.map((row, index) => (
                      <tr key={`${row.engineer || getTechnicianHoursLabel(row)}-${index}`} className="border-t border-gray-100 dark:border-gray-700">
                        <td className="px-4 py-3 text-gray-500">{index + 1}</td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2 min-w-0">
                            <div className="w-8 h-8 rounded-full bg-cyan-50 dark:bg-cyan-900/20 flex items-center justify-center shrink-0">
                              <FaUserCog className="text-cyan-600 dark:text-cyan-300 text-sm" />
                            </div>
                            <span className="truncate text-gray-800 dark:text-gray-100">{getTechnicianHoursLabel(row)}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          {row.engineer ? (
                            <a
                              href={`/app/user/${encodeURIComponent(row.engineer)}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-cyan-700 dark:text-cyan-300 hover:underline truncate inline-block max-w-[220px]"
                            >
                              {row.engineer}
                            </a>
                          ) : (
                            <span className="text-gray-400">—</span>
                          )}
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="inline-flex items-center gap-1 rounded-full bg-cyan-50 dark:bg-cyan-900/20 px-3 py-1 text-cyan-700 dark:text-cyan-300 font-semibold">
                            <FaClock className="text-xs" />
                            {parseTechnicianHours(row.total_hours)} hrs
                          </span>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div className="border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 sm:px-4 py-2 flex flex-wrap items-center justify-between gap-2">
          <div className="text-xs text-gray-600 dark:text-gray-300">
            {t('dashboard.technicianHoursFooter', {
              count: rows.length,
              total: summary.totalHours,
              defaultValue: `Showing ${rows.length} technicians (filtered) • ${summary.totalHours} total hours`,
            })}
          </div>
          <button
            type="button"
            onClick={onClose}
            className="px-3 py-1.5 rounded-md border border-gray-300 dark:border-gray-600 text-xs hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            {t('common.close', { defaultValue: 'Close' })}
          </button>
        </div>
      </div>
    </div>
  );
};

const SummaryCard: React.FC<{
  icon: React.ReactNode;
  label: string;
  value: string;
  theme: 'blue' | 'cyan' | 'purple';
}> = ({ icon, label, value, theme }) => {
  const themeClasses = {
    blue: 'bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-800',
    cyan: 'bg-cyan-50 dark:bg-cyan-900/20 border-cyan-100 dark:border-cyan-800',
    purple: 'bg-purple-50 dark:bg-purple-900/20 border-purple-100 dark:border-purple-800',
  }[theme];

  return (
    <div className={`${compactSummaryCardClass} ${themeClasses}`}>
      <div className="flex items-center gap-1.5 mb-1">
        {icon}
        <div className={compactSummaryLabelClass}>{label}</div>
      </div>
      <div className={compactSummaryValueClass}>{value}</div>
    </div>
  );
};

export default TechnicianWorkingHoursReportModal;
