import React, { useEffect, useRef, useState } from 'react';
import { FaHardHat } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import StackedBarChart from './StackedBarChart';
import type { TechnicianWorkSummaryChartData } from '../services/technicianWorkSummaryService';

type TechnicianWorkedChartCardProps = {
  title: string;
  data: TechnicianWorkSummaryChartData | null;
  loading?: boolean;
  onOpenReport: () => void;
};

const TechnicianWorkedChartCard: React.FC<TechnicianWorkedChartCardProps> = ({
  title,
  data,
  loading = false,
  onOpenReport,
}) => {
  const { t } = useTranslation();
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const subtitle = data
    ? t('dashboard.techniciansWorkedSubtitle', {
        completed: data.totals.completed,
        inProgress: data.totals.in_progress,
        open: data.totals.open,
        defaultValue: `${data.totals.completed} done • ${data.totals.in_progress} wip • ${data.totals.open} open`,
      })
    : t('dashboard.techniciansWorkedEmpty', { defaultValue: 'No technician data' });

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all p-3 border border-gray-200 dark:border-gray-700">
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <h3 className="text-sm font-semibold text-gray-800 dark:text-white truncate">{title}</h3>
            <button
              type="button"
              onClick={onOpenReport}
              className="p-1.5 rounded-lg bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors"
              title={t('dashboard.viewFullReport', { defaultValue: 'View Full Report' })}
            >
              <FaHardHat className="w-3.5 h-3.5" />
            </button>
          </div>
          <p className="text-[11px] text-gray-500 dark:text-gray-400 mt-0.5">{subtitle}</p>
        </div>

        <div className="relative" ref={menuRef}>
          <button
            type="button"
            onClick={() => setMenuOpen(prev => !prev)}
            className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
            aria-label="Chart menu"
          >
            <svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
            </svg>
          </button>
          {menuOpen && (
            <div className="absolute right-0 mt-1 w-44 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-20 py-1">
              <button
                type="button"
                className="w-full text-left px-3 py-2 text-xs text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
                onClick={() => {
                  setMenuOpen(false);
                  onOpenReport();
                }}
              >
                {t('dashboard.viewFullReport', { defaultValue: 'View Full Report' })}
              </button>
            </div>
          )}
        </div>
      </div>

      {loading ? (
        <div className="h-48 flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
        </div>
      ) : !data || !data.datasets.length ? (
        <div className="h-48 flex items-center justify-center text-gray-400 text-xs">
          {t('dashboard.noChartData', { defaultValue: 'No chart data available' })}
        </div>
      ) : (
        <StackedBarChart labels={data.labels} datasets={data.datasets} />
      )}
    </div>
  );
};

export default TechnicianWorkedChartCard;
