import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { FaClipboardList, FaSync, FaTimes } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import { buildWoUrl } from '../utils/buildWoUrl';
import type { DashboardLocationFilters } from '../utils/hospitalUtils';
import type { AssetDeviceStatusSummaryFilters } from '../services/assetDeviceStatusService';
import {
  compactFilterFieldWrapClass,
  compactFilterInputClass,
  compactFilterLabelClass,
  compactSummaryCardClass,
  compactSummaryLabelClass,
  compactSummaryValueClass,
  compactToolbarBtnPrimary,
} from '../utils/reportModalStyles';

type ChartDataset = {
  name?: string;
  values?: number[];
  color?: string;
  colors?: string[];
};

type TypeStatusChartData = {
  labels?: string[];
  datasets?: ChartDataset[];
};

type WorkOrderStatusRefreshResult = {
  chart: TypeStatusChartData | null;
  total: number;
};

type WorkOrderStatusReportModalProps = {
  isOpen: boolean;
  onClose: () => void;
  initialChartData?: TypeStatusChartData | null;
  defaultFromDate?: string;
  defaultToDate?: string;
  locationFilters?: DashboardLocationFilters;
  workOrderType?: string;
  onRefresh?: (filters: AssetDeviceStatusSummaryFilters & { work_order_type?: string }) => Promise<WorkOrderStatusRefreshResult>;
};

const APP_BASE = '/asm_app';

const STATUS_HEADER_COLORS: Record<string, string> = {
  Open: 'text-amber-700 dark:text-amber-300',
  'Work In Progress': 'text-blue-700 dark:text-blue-300',
  'Pending Review': 'text-rose-700 dark:text-rose-300',
  Completed: 'text-green-700 dark:text-green-400',
  Closed: 'text-purple-700 dark:text-purple-300',
  Rejected: 'text-red-700 dark:text-red-400',
  Cancelled: 'text-gray-600 dark:text-gray-300',
};

const WorkOrderStatusReportModal: React.FC<WorkOrderStatusReportModalProps> = ({
  isOpen,
  onClose,
  initialChartData = null,
  defaultFromDate = '',
  defaultToDate = '',
  locationFilters,
  workOrderType = '',
  onRefresh,
}) => {
  const { t } = useTranslation();
  const [fromDate, setFromDate] = useState(defaultFromDate);
  const [toDate, setToDate] = useState(defaultToDate);
  const [chartData, setChartData] = useState<TypeStatusChartData | null>(initialChartData);
  const [totalWorkOrders, setTotalWorkOrders] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!isOpen) return;
    setFromDate(defaultFromDate);
    setToDate(defaultToDate);
    setChartData(initialChartData);
    setError(null);
  }, [isOpen, defaultFromDate, defaultToDate, initialChartData]);

  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(() => {
    const filters: AssetDeviceStatusSummaryFilters & { work_order_type?: string } = {};
    if (locationFilters?.company) filters.company = locationFilters.company;
    if (locationFilters?.site_name) filters.site_name = locationFilters.site_name;
    if (fromDate) filters.from_date = fromDate;
    if (toDate) filters.to_date = toDate;
    if (workOrderType) filters.work_order_type = workOrderType;
    return filters;
  }, [fromDate, toDate, locationFilters, workOrderType]);

  const loadData = useCallback(async () => {
    if (!onRefresh) return;

    setLoading(true);
    setError(null);
    try {
      const result = await onRefresh(buildFilters());
      setChartData(result.chart);
      setTotalWorkOrders(result.total);
    } catch (err) {
      setChartData(null);
      setTotalWorkOrders(0);
      setError(err instanceof Error ? err.message : 'Failed to load report data');
    } finally {
      setLoading(false);
    }
  }, [onRefresh, buildFilters]);

  useEffect(() => {
    if (!isOpen || !onRefresh) return;
    loadData();
  }, [isOpen, onRefresh]); // eslint-disable-line react-hooks/exhaustive-deps

  const typeRows = useMemo(() => {
    const labels = chartData?.labels || [];
    const datasets = chartData?.datasets || [];
    return labels.map((label, rowIndex) => ({
      label,
      cells: datasets.map(dataset => Number(dataset.values?.[rowIndex]) || 0),
      rowTotal: datasets.reduce((sum, dataset) => sum + (Number(dataset.values?.[rowIndex]) || 0), 0),
    }));
  }, [chartData]);

  const typeColumns = chartData?.datasets?.map(dataset => dataset.name || '') || [];

  const columnTotals = useMemo(
    () =>
      typeColumns.map((_column, columnIndex) =>
        typeRows.reduce((sum, row) => sum + (row.cells[columnIndex] || 0), 0)
      ),
    [typeColumns, typeRows]
  );

  const computedTotal = useMemo(
    () => typeRows.reduce((sum, row) => sum + row.rowTotal, 0),
    [typeRows]
  );

  const displayTotal = totalWorkOrders || computedTotal;

  const navigateToWorkOrders = (params: { work_order_type?: string; status?: string }) => {
    const path = buildWoUrl(
      {
        work_order_type: params.work_order_type || workOrderType || undefined,
        status: params.status,
        company: locationFilters?.company,
        site_name: locationFilters?.site_name,
      },
      fromDate || undefined,
      toDate || undefined,
      locationFilters
    );
    onClose();
    window.location.href = `${APP_BASE}${path}`;
  };

  const handleTypeClick = (typeLabel: string) => {
    navigateToWorkOrders({ work_order_type: typeLabel });
  };

  const handleCellClick = (typeLabel: string, status: string, value: number) => {
    if (value <= 0) return;
    navigateToWorkOrders({ work_order_type: typeLabel, status });
  };

  const handleStatusTotalClick = (status: string, value: number) => {
    if (value <= 0) return;
    navigateToWorkOrders({ status });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[80] flex items-center justify-center p-4">
      <button type="button" className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} aria-label="Close" />

      <div className="relative w-full max-w-5xl max-h-[90vh] overflow-hidden rounded-xl bg-white dark:bg-gray-900 shadow-2xl flex flex-col">
        <div className="bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-4 py-3">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-center gap-2 min-w-0">
              <div className="p-1.5 rounded-lg bg-white/15 shrink-0">
                <FaClipboardList className="w-4 h-4" />
              </div>
              <div className="min-w-0">
                <h2 className="text-base font-semibold truncate">
                  {t('dashboard.workOrderStatus', { defaultValue: 'Work Order Status' })}
                </h2>
                <p className="text-xs text-white/85 mt-0.5">
                  {t('dashboard.workOrderTypeStatusHint', {
                    defaultValue: 'Type vs status counts — click a number to view filtered work orders',
                  })}
                </p>
              </div>
            </div>
            <button type="button" onClick={onClose} className="p-1.5 rounded-lg hover:bg-white/10">
              <FaTimes className="text-sm" />
            </button>
          </div>
        </div>

        <div className="px-3 py-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
          <div className="flex flex-wrap items-end gap-2">
            <div className={`${compactFilterFieldWrapClass} mb-0 w-[8.5rem]`}>
              <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} mb-0 w-[8.5rem]`}>
              <label className={compactFilterLabelClass}>
                {t('dashboard.toDate', { defaultValue: 'To Date' })}
              </label>
              <input
                type="date"
                value={toDate}
                onChange={e => setToDate(e.target.value)}
                className={compactFilterInputClass}
              />
            </div>
            <button
              type="button"
              onClick={loadData}
              disabled={loading || !onRefresh}
              className={`${compactToolbarBtnPrimary('purple')} mb-0.5`}
            >
              <FaSync className={`text-[10px] ${loading ? 'animate-spin' : ''}`} />
              {t('dashboard.refreshReport', { defaultValue: 'Refresh' })}
            </button>
            {(locationFilters?.company || locationFilters?.site_name) && (
              <div className="flex flex-wrap gap-1.5 ml-auto pb-0.5">
                {locationFilters?.company && (
                  <span className="px-2 py-0.5 rounded-full bg-white dark:bg-gray-800 border border-indigo-200 dark:border-indigo-800 text-indigo-800 dark:text-indigo-200 text-[10px]">
                    {locationFilters.company}
                  </span>
                )}
                {locationFilters?.site_name && (
                  <span className="px-2 py-0.5 rounded-full bg-white dark:bg-gray-800 border border-indigo-200 dark:border-indigo-800 text-indigo-800 dark:text-indigo-200 text-[10px]">
                    {locationFilters.site_name}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>

        <div className="px-3 py-2 border-b border-gray-200 dark:border-gray-700">
          <div className={`${compactSummaryCardClass} border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/20 inline-block min-w-[8rem]`}>
            <div className={compactSummaryLabelClass}>
              {t('dashboard.totalWorkOrders', { defaultValue: 'Total Work Orders' })}
            </div>
            <div className={`${compactSummaryValueClass} text-indigo-700 dark:text-indigo-300`}>
              {displayTotal.toLocaleString()}
            </div>
          </div>
        </div>

        <div className="overflow-y-auto flex-1">
          {error && (
            <div className="mx-3 mt-3 rounded-md border border-red-200 bg-red-50 text-red-700 px-3 py-2 text-xs">
              {error}
            </div>
          )}

          <table className="min-w-full text-xs">
            <thead className="bg-gray-50 dark:bg-gray-800/80 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-200">
                  {t('dashboard.woType', { defaultValue: 'WO Type' })}
                </th>
                {typeColumns.map(column => (
                  <th
                    key={column}
                    className={`px-3 py-2 text-right font-semibold whitespace-nowrap ${STATUS_HEADER_COLORS[column] || 'text-gray-700 dark:text-gray-200'}`}
                  >
                    {column}
                  </th>
                ))}
                <th className="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-200">
                  {t('dashboard.totalWorkOrders', { defaultValue: 'Total' })}
                </th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={typeColumns.length + 2} className="px-3 py-8 text-center text-gray-500">
                    {t('common.loading', { defaultValue: 'Loading...' })}
                  </td>
                </tr>
              ) : typeRows.length === 0 ? (
                <tr>
                  <td colSpan={typeColumns.length + 2} className="px-3 py-8 text-center text-gray-500">
                    {t('common.noData', { defaultValue: 'No data' })}
                  </td>
                </tr>
              ) : (
                typeRows.map(row => (
                  <tr key={row.label} className="border-t border-gray-100 dark:border-gray-800">
                    <td className="px-3 py-2">
                      <button
                        type="button"
                        onClick={() => handleTypeClick(row.label)}
                        className="text-left font-medium text-indigo-700 dark:text-indigo-300 hover:underline"
                      >
                        {row.label}
                      </button>
                    </td>
                    {row.cells.map((value, index) => (
                      <td key={`${row.label}-${typeColumns[index]}`} className="px-3 py-2 text-right">
                        <CountButton
                          value={value}
                          onClick={() => handleCellClick(row.label, typeColumns[index], value)}
                        />
                      </td>
                    ))}
                    <td className="px-3 py-2 text-right font-semibold text-gray-900 dark:text-white">
                      {row.rowTotal}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
            {!loading && typeRows.length > 0 && (
              <tfoot>
                <tr className="border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/80">
                  <td className="px-3 py-2 font-semibold text-gray-800 dark:text-gray-100">
                    {t('dashboard.totalWorkOrders', { defaultValue: 'Total' })}
                  </td>
                  {columnTotals.map((value, index) => (
                    <td key={`total-${typeColumns[index]}`} className="px-3 py-2 text-right">
                      <CountButton
                        value={value}
                        onClick={() => handleStatusTotalClick(typeColumns[index], value)}
                        bold
                      />
                    </td>
                  ))}
                  <td className="px-3 py-2 text-right font-semibold text-gray-900 dark:text-white">
                    {computedTotal}
                  </td>
                </tr>
              </tfoot>
            )}
          </table>
        </div>
      </div>
    </div>
  );
};

const CountButton: React.FC<{
  value: number;
  onClick: () => void;
  bold?: boolean;
}> = ({ value, onClick, bold = false }) => {
  if (value <= 0) {
    return <span className="text-gray-400">0</span>;
  }

  return (
    <button
      type="button"
      onClick={onClick}
      className={`${bold ? 'font-semibold' : 'font-medium'} text-gray-900 dark:text-white hover:text-indigo-600 dark:hover:text-indigo-300 hover:underline`}
    >
      {value.toLocaleString()}
    </button>
  );
};

export default WorkOrderStatusReportModal;
