import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { FaBoxes, FaExternalLinkAlt, FaSync, FaTimes } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import type { PieChartData } from './PieChart';
import { buildAssetUrl } from '../utils/buildAssetUrl';
import type { DashboardLocationFilters } from '../utils/hospitalUtils';
import type { AssetDeviceStatusSummaryFilters } from '../services/assetDeviceStatusService';
import {
  compactFilterFieldWrapClass,
  compactFilterInputClass,
  compactFilterLabelClass,
  compactToolbarBtnPrimary,
} from '../utils/reportModalStyles';

export type AssetStatusReportRow = {
  name: string;
  asset_name?: string;
  custom_device_status?: string;
  location?: string;
  department?: string;
  company?: string;
  custom_site?: string;
};

type AssetStatusRefreshResult = {
  chart: PieChartData | null;
  total_assets: number;
  assets: AssetStatusReportRow[];
};

type AssetStatusReportModalProps = {
  isOpen: boolean;
  onClose: () => void;
  chartData: PieChartData | null;
  defaultFromDate?: string;
  defaultToDate?: string;
  locationFilters?: DashboardLocationFilters;
  onRefresh?: (filters: AssetDeviceStatusSummaryFilters) => Promise<AssetStatusRefreshResult>;
};

type StatusCardStyle = {
  bg: string;
  border: string;
  text: string;
  bar: string;
};

const getStatusCardStyle = (label: string, chartColor?: string): StatusCardStyle => {
  const key = (label || '').trim().toLowerCase();

  if (key === 'up') {
    return { bg: 'bg-emerald-50 dark:bg-emerald-900/20', border: 'border-emerald-200 dark:border-emerald-800', text: 'text-emerald-700 dark:text-emerald-300', bar: '#10B981' };
  }
  if (key === 'down') {
    return { bg: 'bg-red-50 dark:bg-red-900/20', border: 'border-red-200 dark:border-red-800', text: 'text-red-700 dark:text-red-300', bar: '#EF4444' };
  }
  if (key.includes('maintenance')) {
    return { bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-amber-200 dark:border-amber-800', text: 'text-amber-700 dark:text-amber-300', bar: '#F59E0B' };
  }
  if (key.includes('decommission')) {
    return { bg: 'bg-gray-50 dark:bg-gray-800', border: 'border-gray-200 dark:border-gray-700', text: 'text-gray-600 dark:text-gray-300', bar: '#6B7280' };
  }

  return {
    bg: 'bg-indigo-50 dark:bg-indigo-900/20',
    border: 'border-indigo-200 dark:border-indigo-800',
    text: 'text-indigo-700 dark:text-indigo-300',
    bar: chartColor || '#6366F1',
  };
};

const APP_BASE = '/asm_app';

const AssetStatusReportModal: React.FC<AssetStatusReportModalProps> = ({
  isOpen,
  onClose,
  chartData,
  defaultFromDate = '',
  defaultToDate = '',
  locationFilters,
  onRefresh,
}) => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [fromDate, setFromDate] = useState(defaultFromDate);
  const [toDate, setToDate] = useState(defaultToDate);
  const [localChartData, setLocalChartData] = useState<PieChartData | null>(chartData);

  useEffect(() => {
    if (!isOpen) return;
    setFromDate(defaultFromDate);
    setToDate(defaultToDate);
    setLocalChartData(chartData);
  }, [isOpen, defaultFromDate, defaultToDate, chartData]);

  const buildFilters = useCallback((): AssetDeviceStatusSummaryFilters => {
    const filters: AssetDeviceStatusSummaryFilters = {};
    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;
    return filters;
  }, [fromDate, toDate, locationFilters]);

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

    setLoading(true);
    try {
      const result = await onRefresh(buildFilters());
      setLocalChartData(result.chart);
    } catch (err) {
      console.error('Failed to load asset status overview:', err);
      setLocalChartData(null);
    } finally {
      setLoading(false);
    }
  }, [onRefresh, buildFilters]);

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

  const totalAssets = localChartData?.total ?? 0;

  const statusRows = useMemo(() => {
    const labels = localChartData?.labels || [];
    const values = localChartData?.datasets?.[0]?.values || [];
    const colors = localChartData?.datasets?.[0]?.colors || [];

    return labels.map((label, index) => ({
      label,
      count: Number(values[index]) || 0,
      color: colors[index],
      percentage: totalAssets > 0 ? ((Number(values[index]) || 0) / totalAssets) * 100 : 0,
    }));
  }, [localChartData, totalAssets]);

  const navigateToAssets = useCallback(
    (deviceStatus?: string) => {
      const path = buildAssetUrl(
        { device_status: deviceStatus, ...locationFilters },
        fromDate,
        toDate,
        locationFilters
      );
      window.location.href = `${APP_BASE}${path}`;
    },
    [fromDate, toDate, locationFilters]
  );

  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-2xl 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-teal-500 to-emerald-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">
                <FaBoxes className="w-4 h-4" />
              </div>
              <div>
                <h2 className="text-base font-semibold">
                  {t('dashboard.assetStatusOverview', { defaultValue: 'Asset Status Overview' })}
                </h2>
                <p className="text-xs text-white/85 mt-0.5">
                  {t('dashboard.clickStatusCardHint', { defaultValue: 'Click a card to view filtered assets' })}
                </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 bg-teal-50 dark:bg-teal-900/20 border-b border-teal-100 dark:border-teal-900/40">
          <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('emerald')} 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-teal-200 dark:border-teal-800 text-teal-800 dark:text-teal-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-teal-200 dark:border-teal-800 text-teal-800 dark:text-teal-200 text-[10px]">
                    {locationFilters.site_name}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>

        <div className="p-3 overflow-y-auto flex-1 space-y-3">
          <button
            type="button"
            onClick={() => navigateToAssets()}
            className="w-full text-left rounded-lg border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/20 p-3 hover:shadow-md transition-all group"
          >
            <div className="flex items-center justify-between gap-3">
              <div>
                <div className="text-xl font-bold text-indigo-700 dark:text-indigo-300">{totalAssets.toLocaleString()}</div>
                <div className="text-xs font-medium text-indigo-600 dark:text-indigo-300 mt-0.5">
                  {t('dashboard.totalAssets', { defaultValue: 'Total Assets' })}
                </div>
              </div>
              <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-indigo-600 dark:text-indigo-300 group-hover:underline">
                {t('dashboard.viewAll', { defaultValue: 'View all' })}
                <FaExternalLinkAlt className="w-2.5 h-2.5" />
              </span>
            </div>
          </button>

          {loading ? (
            <div className="py-8 flex justify-center">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-teal-600" />
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {statusRows.map((row) => {
                const style = getStatusCardStyle(row.label, row.color);
                return (
                  <button
                    key={row.label}
                    type="button"
                    onClick={() => navigateToAssets(row.label)}
                    className={`text-left rounded-lg border p-3 transition-all hover:shadow-md group ${style.bg} ${style.border}`}
                  >
                    <div className={`text-lg font-bold ${style.text}`}>{row.count.toLocaleString()}</div>
                    <div className={`text-[10px] font-semibold uppercase tracking-wide mt-0.5 ${style.text}`}>{row.label}</div>
                    <div className="mt-2 h-1.5 rounded-full bg-white/70 dark:bg-gray-900/30 overflow-hidden">
                      <div className="h-full rounded-full" style={{ width: `${row.percentage}%`, backgroundColor: style.bar }} />
                    </div>
                    <div className="mt-1.5 flex items-center justify-between text-[10px] text-gray-600 dark:text-gray-400">
                      <span>{row.percentage.toFixed(1)}% {t('dashboard.ofTotal', { defaultValue: 'of total' })}</span>
                      <span className="opacity-0 group-hover:opacity-100 transition-opacity font-medium">
                        {t('dashboard.viewFiltered', { defaultValue: 'View ↗' })}
                      </span>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default AssetStatusReportModal;
