import React from 'react';
import { Clock, Wrench, AlertTriangle, Zap } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { Equipment, MaintenanceHistory } from '../../../api/types/equipment';
import { statusColors } from '../../../styles/colors';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

interface MaintenanceHistoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  equipment: Equipment;
  loading?: boolean;
}

/**
 * MaintenanceHistoryModal - Modal for viewing equipment maintenance history
 * Shows maintenance records with color-coded types and detailed information
 */
export const MaintenanceHistoryModal: React.FC<MaintenanceHistoryModalProps> = ({
  isOpen,
  onClose,
  equipment,
  loading = false
}) => {
  const { t } = useTranslation(['equipment', 'common']);
  const { currencySymbol } = useTenantCurrency();

  // Get maintenance type display info with colors and icons
  const getMaintenanceTypeInfo = (type: MaintenanceHistory['type']) => {
    switch (type) {
      case 'preventive':
        return {
          label: t('maintenance.type.preventive', 'Preventivo'),
          icon: Wrench,
          color: statusColors.inProgress.primary,
          bgColor: `${statusColors.inProgress.primary}15`
        };
      case 'corrective':
        return {
          label: t('maintenance.type.corrective', 'Correctivo'),
          icon: AlertTriangle,
          color: statusColors.pending.primary,
          bgColor: `${statusColors.pending.primary}15`
        };
      case 'emergency':
        return {
          label: t('maintenance.type.emergency', 'Emergencia'),
          icon: Zap,
          color: statusColors.out.primary,
          bgColor: `${statusColors.out.primary}15`
        };
      default:
        return {
          label: type,
          icon: Wrench,
          color: statusColors.normal.primary,
          bgColor: `${statusColors.normal.primary}15`
        };
    }
  };

  // Process maintenance history for display
  const maintenanceRecords = equipment.maintenanceHistory || [];
  const sortedRecords = [...maintenanceRecords].sort((a, b) =>
    new Date(b.date).getTime() - new Date(a.date).getTime()
  );

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: `${maintenanceRecords.length} ${t('maintenance.records', 'registros')}`,
    icon: Clock
  };

  // Create maintenance list display
  const maintenanceList = sortedRecords.length > 0 ? (
    <div className="space-y-3 max-h-96 overflow-y-auto">
      {sortedRecords.map((record) => {
        const typeInfo = getMaintenanceTypeInfo(record.type);
        const MaintenanceIcon = typeInfo.icon;

        return (
          <div
            key={record.id}
            className="flex items-start gap-3 p-4 bg-[var(--surface-secondary)] rounded-lg hover:bg-[var(--surface-tertiary)] transition-colors border border-[var(--border-primary)]"
          >
            {/* Icon and type */}
            <div
              className="flex-shrink-0 p-2 rounded-lg"
              style={{ backgroundColor: typeInfo.bgColor }}
            >
              <MaintenanceIcon
                className="w-5 h-5"
                style={{ color: typeInfo.color }}
              />
            </div>

            {/* Main content */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between mb-2">
                <span className="font-medium text-[var(--text-primary)]">
                  {record.description}
                </span>
                <span
                  className="px-2 py-1 text-xs font-medium rounded"
                  style={{
                    backgroundColor: typeInfo.bgColor,
                    color: typeInfo.color
                  }}
                >
                  {typeInfo.label}
                </span>
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm text-[var(--text-secondary)] mb-2">
                <div>
                  <span className="text-[var(--text-tertiary)]">{t('fields.date', 'Fecha')}:</span>
                  <span className="ml-1">
                    {new Date(record.date).toLocaleDateString('es-ES', {
                      year: 'numeric',
                      month: 'short',
                      day: 'numeric'
                    })}
                  </span>
                </div>
                <div>
                  <span className="text-[var(--text-tertiary)]">{t('fields.technician', 'Técnico')}:</span>
                  <span className="ml-1">{record.technician}</span>
                </div>
                <div>
                  <span className="text-[var(--text-tertiary)]">{t('common:actions.cost', 'Coste')}:</span>
                  <span className="ml-1 font-medium">{currencySymbol}{record.cost.toFixed(2)}</span>
                </div>
                <div>
                  <span className="text-[var(--text-tertiary)]">{t('fields.downtime', 'Parada')}:</span>
                  <span className="ml-1 font-medium">{record.downtime}h</span>
                </div>
              </div>

              {record.partsUsed && record.partsUsed.length > 0 && (
                <div className="mt-2">
                  <span className="text-xs text-[var(--text-tertiary)]">
                    {t('fields.parts', 'Repuestos')}:
                  </span>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {record.partsUsed.map((part, index) => (
                      <span
                        key={index}
                        className="px-2 py-0.5 bg-[var(--bg-tertiary)] text-xs rounded border border-[var(--border-primary)]"
                      >
                        {part}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  ) : (
    <div className="text-center py-12 text-[var(--text-secondary)]">
      <Wrench className="w-16 h-16 mx-auto mb-4 opacity-30" />
      <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
        {t('maintenance.no_history', 'No hay historial de mantenimiento')}
      </h3>
      <p className="text-sm">
        {t('maintenance.no_history_description', 'Los registros de mantenimiento aparecerán aquí cuando se realicen operaciones')}
      </p>
    </div>
  );

  const sections = [
    {
      title: t('maintenance.history', 'Historial de Mantenimiento'),
      icon: Clock,
      fields: [
        {
          label: '',
          value: maintenanceList,
          span: 2 as const
        }
      ]
    }
  ];

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode="view"
      title={equipment.name}
      subtitle={`${equipment.model || equipment.type} • ${maintenanceRecords.length} ${t('maintenance.records', 'registros')}`}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading}
      showDefaultActions={false}
    />
  );
};

export default MaintenanceHistoryModal;
