import React from 'react';
import { Calendar, Wrench } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { AddModal, AddModalSection } from '../../ui/AddModal/AddModal';
import { Equipment } from '../../../api/types/equipment';
import { statusColors } from '../../../styles/colors';

interface ScheduleMaintenanceModalProps {
  isOpen: boolean;
  onClose: () => void;
  equipment: Equipment;
  onSchedule: (equipmentId: string, maintenanceData: MaintenanceScheduleData) => Promise<void>;
  isLoading?: boolean;
}

export interface MaintenanceScheduleData {
  type: 'preventive' | 'corrective' | 'emergency';
  scheduledDate: string;
  scheduledTime: string;
  estimatedDuration: number;
  technician: string;
  partsNeeded: string;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  description: string;
}

/**
 * ScheduleMaintenanceModal - Modal for scheduling equipment maintenance
 * Uses AddModal component for consistent UX across the application
 */
export const ScheduleMaintenanceModal: React.FC<ScheduleMaintenanceModalProps> = ({
  isOpen,
  onClose,
  equipment,
  onSchedule,
  isLoading = false
}) => {
  const { t } = useTranslation(['equipment', 'common']);

  const handleSave = async (formData: Record<string, any>) => {
    const maintenanceData: MaintenanceScheduleData = {
      type: formData.type as MaintenanceScheduleData['type'],
      scheduledDate: formData.scheduledDate,
      scheduledTime: formData.scheduledTime,
      estimatedDuration: Number(formData.estimatedDuration),
      technician: formData.technician,
      partsNeeded: formData.partsNeeded || '',
      priority: formData.priority as MaintenanceScheduleData['priority'],
      description: formData.description
    };

    await onSchedule(equipment.id, maintenanceData);
  };

  const sections: AddModalSection[] = [
    {
      title: t('sections.maintenance_info', 'Información de Mantenimiento'),
      icon: Wrench,
      columns: 2,
      fields: [
        {
          label: t('fields.maintenance_type', 'Tipo de Mantenimiento'),
          name: 'type',
          type: 'select',
          required: true,
          defaultValue: 'preventive',
          options: [
            { label: t('maintenance.type.preventive', 'Preventivo'), value: 'preventive' },
            { label: t('maintenance.type.corrective', 'Correctivo'), value: 'corrective' },
            { label: t('maintenance.type.emergency', 'Emergencia'), value: 'emergency' }
          ]
        },
        {
          label: t('fields.priority', 'Prioridad'),
          name: 'priority',
          type: 'select',
          required: true,
          defaultValue: 'medium',
          options: [
            { label: t('priority.low', 'Baja'), value: 'low' },
            { label: t('priority.medium', 'Media'), value: 'medium' },
            { label: t('priority.high', 'Alta'), value: 'high' },
            { label: t('priority.urgent', 'Urgente'), value: 'urgent' }
          ]
        }
      ]
    },
    {
      title: t('sections.scheduling', 'Programación'),
      icon: Calendar,
      columns: 2,
      fields: [
        {
          label: t('fields.scheduled_date', 'Fecha Programada'),
          name: 'scheduledDate',
          type: 'date',
          required: true,
          defaultValue: new Date().toISOString().split('T')[0]
        },
        {
          label: t('fields.time', 'Hora'),
          name: 'scheduledTime',
          type: 'text',
          required: false,
          defaultValue: '09:00',
          placeholder: 'HH:MM'
        },
        {
          label: t('fields.technician', 'Técnico Asignado'),
          name: 'technician',
          type: 'text',
          required: true,
          placeholder: t('placeholders.technician', 'Nombre del técnico'),
          span: 2
        },
        {
          label: t('fields.duration', 'Duración (horas)'),
          name: 'estimatedDuration',
          type: 'number',
          required: true,
          defaultValue: 2,
          validation: (value: number) => {
            if (value <= 0) {
              return t('validation.must_be_positive', 'Debe ser mayor que 0');
            }
            return null;
          }
        }
      ]
    },
    {
      title: t('sections.details', 'Detalles'),
      icon: Wrench,
      columns: 1,
      fields: [
        {
          label: t('fields.description', 'Descripción'),
          name: 'description',
          type: 'textarea',
          required: true,
          placeholder: t('placeholders.maintenance_description', 'Descripción del trabajo a realizar'),
          span: 2
        },
        {
          label: t('fields.parts_needed', 'Repuestos Necesarios'),
          name: 'partsNeeded',
          type: 'textarea',
          required: false,
          placeholder: t('placeholders.parts_needed', 'Lista de repuestos y materiales necesarios'),
          span: 2
        }
      ]
    }
  ];

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title={t('actions.schedule_maintenance', 'Programar Mantenimiento')}
      subtitle={`${equipment.name} • ${equipment.model || equipment.type}`}
      statusIndicator={{
        color: statusColors.inProgress.primary,
        text: t('maintenance.scheduled', 'Programado'),
        icon: Calendar,
        isHighlight: true
      }}
      sections={sections}
      onSave={handleSave}
      size="lg"
      loading={isLoading}
    />
  );
};

export default ScheduleMaintenanceModal;
