import React, { useEffect, useRef, useState } from 'react';
import { FaUserClock } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import HorizontalBarChart from './HorizontalBarChart';
import type { TechnicianWorkingHoursChartData } from '../services/technicianWorkingHoursService';

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

const TechnicianHoursChartCard: React.FC<TechnicianHoursChartCardProps> = ({
  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 totalHours = data?.totalHours ?? 0;
  const subtitle = data
    ? t('dashboard.technicianHoursSubtitle', {
        total: Math.round(totalHours * 100) / 100,
        defaultValue: `Total: ${Math.round(totalHours * 100) / 100} hrs`,
      })
    : t('dashboard.technicianHoursEmpty', { defaultValue: 'No technician hours 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">
            <button
              type="button"
              onClick={onOpenReport}
              className="p-1.5 rounded-full bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-300 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 transition-colors shrink-0"
              title={t('dashboard.viewFullReport', { defaultValue: 'View Full Report' })}
            >
              <FaUserClock className="w-3.5 h-3.5" />
            </button>
            <div className="min-w-0">
              <h3 className="text-sm font-semibold text-gray-800 dark:text-white truncate">{title}</h3>
              <p className="text-[11px] text-indigo-600 dark:text-indigo-300 mt-0.5">{subtitle}</p>
            </div>
          </div>
        </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 flex-col items-center justify-center gap-2">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" />
          <span className="text-xs text-gray-500">
            {t('dashboard.loadingTechnicianHours', { defaultValue: 'Loading technician hours…' })}
          </span>
        </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>
      ) : (
        <HorizontalBarChart labels={data.labels} datasets={data.datasets} valueLabel="hrs" />
      )}
    </div>
  );
};

export default TechnicianHoursChartCard;
