import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertTriangle, Camera, CheckCircle, Clock, FileText, HelpCircle, Mail, Phone, User, Settings } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Input, Textarea, Select, SelectItem, FileUpload, Alert, type SelectOption } from '../../../components/ui';
import { Equipment } from '../../../api/types/equipment';
import { useToast } from '../../../hooks/useToast';

interface ReportFailureModalProps {
  isOpen: boolean;
  onClose: () => void;
  equipment: Equipment;
  onReportFailure: (failureData: {
    failureType: string;
    severity: string;
    description: string;
    photos?: File[];
    estimatedImpact: boolean;
  }) => Promise<void>;
  isLoading?: boolean;
}

export const ReportFailureModal: React.FC<ReportFailureModalProps> = ({
  isOpen,
  onClose,
  equipment,
  onReportFailure,
  isLoading = false
}) => {
  const { t } = useTranslation(['equipment', 'common']);
  const { showToast } = useToast();
  
  const [failureType, setFailureType] = useState<string>('mechanical');
  const [severity, setSeverity] = useState<string>('high');
  const [description, setDescription] = useState<string>('');
  const [photos, setPhotos] = useState<File[]>([]);
  const [estimatedImpact, setEstimatedImpact] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const failureTypes: SelectOption[] = [
    { value: 'mechanical', label: t('failure_types.mechanical') || 'Mechanical' },
    { value: 'electrical', label: t('failure_types.electrical') || 'Electrical' },
    { value: 'software', label: t('failure_types.software') || 'Software' },
    { value: 'temperature', label: t('failure_types.temperature') || 'Temperature' },
    { value: 'other', label: t('failure_types.other') || 'Other' }
  ];

  const severityOptions: SelectOption[] = [
    { value: 'high', label: t('severity.high') || 'High' },
    { value: 'urgent', label: t('severity.urgent') || 'Urgent' },
    { value: 'medium', label: t('severity.medium') || 'Medium' },
    { value: 'low', label: t('severity.low') || 'Low' }
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!description.trim()) {
      setError(t('errors.description_required') || 'Description is required');
      return;
    }

    try {
      await onReportFailure({
        failureType,
        severity,
        description,
        photos,
        estimatedImpact
      });
      
      showToast({
        title: t('success.failure_reported') || 'Failure Reported',
        message: t('success.failure_reported_message', { equipment: equipment.name }) || `Failure for ${equipment.name} has been reported successfully`,
        type: 'success'
      });
      
      // Reset form
      setDescription('');
      setPhotos([]);
      setEstimatedImpact(true);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : t('errors.report_failed') || 'Failed to report failure');
      showToast({
        title: t('errors.report_failed') || 'Report Failed',
        message: err instanceof Error ? err.message : t('errors.try_again') || 'Please try again',
        type: 'error'
      });
    }
  };

  const handlePhotoUpload = (files: File[]) => {
    setPhotos(files);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="lg">
      <form onSubmit={handleSubmit}>
        <ModalHeader>
          <div className="flex items-center gap-2">
            <AlertTriangle className="text-red-500" />
            <h3 className="text-lg font-semibold text-[var(--text-primary)]">
              {t('report_failure.title', { equipment: equipment.name }) || `Report Failure: ${equipment.name}`}
            </h3>
          </div>
        </ModalHeader>

        <ModalBody>
          {error && (
            <Alert type="error" className="mb-4">
              {error}
            </Alert>
          )}

          <div className="space-y-4">
            {/* Equipment Info */}
            <div className="bg-[var(--background-secondary)] p-3 rounded-lg">
              <h4 className="font-medium text-[var(--text-primary)] mb-2 flex items-center gap-2">
                <Settings className="h-4 w-4" />
                {t('equipment_info.title') || 'Equipment Information'}
              </h4>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="flex items-center gap-2">
                  <span className="text-[var(--text-secondary)]">{t('fields.type') || 'Type'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">{equipment.type}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[var(--text-secondary)]">{t('fields.model') || 'Model'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">{equipment.model || 'N/A'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[var(--text-secondary)]">{t('fields.location') || 'Location'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">{equipment.location || 'N/A'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[var(--text-secondary)]">{t('fields.serial_number') || 'Serial'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">{equipment.serialNumber || 'N/A'}</span>
                </div>
              </div>
            </div>

            {/* Failure Type */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('fields.failure_type') || 'Failure Type'}
                </label>
                <Select
                  value={failureType}
                  onChange={(value) => setFailureType(value as string)}
                  options={failureTypes}
                  placeholder={t('common:forms.select_option') || 'Select failure type'}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('fields.severity') || 'Severity'}
                </label>
                <Select
                  value={severity}
                  onChange={(value) => setSeverity(value as string)}
                  options={severityOptions}
                  placeholder={t('common:forms.select_option') || 'Select severity'}
                />
              </div>
            </div>

            {/* Description */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.description') || 'Description'}
              </label>
              <Textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder={t('placeholders.failure_description') || 'Describe the failure in detail...'}
                rows={4}
                required
              />
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('hints.failure_description') || 'Include symptoms, error messages, and any troubleshooting steps attempted'}
              </p>
            </div>

            {/* Photos */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.photos') || 'Photos (Optional)'}
              </label>
              <FileUpload
                accept="image/*"
                multiple
                onChange={handlePhotoUpload}
                maxFiles={5}
                maxSize={5 * 1024 * 1024} // 5MB
              />
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('hints.failure_photos') || 'Upload photos showing the issue (max 5MB each)'}
              </p>
            </div>

            {/* Estimated Impact */}
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="estimatedImpact"
                checked={estimatedImpact}
                onChange={(e) => setEstimatedImpact(e.target.checked)}
                className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label htmlFor="estimatedImpact" className="text-sm text-[var(--text-primary)]">
                {t('fields.estimated_impact') || 'This failure affects production'}
              </label>
              <HelpCircle className="h-4 w-4 text-[var(--text-secondary)]" />
            </div>

            {/* Support Contact Info */}
            {equipment.support_contact && (
              <div className="bg-[var(--background-tertiary)] p-3 rounded-lg">
                <h4 className="font-medium text-[var(--text-primary)] mb-2 flex items-center gap-2">
                  <User className="h-4 w-4" />
                  {t('support_contact.title') || 'Support Contact'}
                </h4>
                <div className="space-y-1 text-sm">
                  {equipment.support_contact.email && (
                    <div className="flex items-center gap-2">
                      <Mail className="h-4 w-4 text-[var(--text-secondary)]" />
                      <span>{equipment.support_contact.email}</span>
                    </div>
                  )}
                  {equipment.support_contact.phone && (
                    <div className="flex items-center gap-2">
                      <Phone className="h-4 w-4 text-[var(--text-secondary)]" />
                      <span>{equipment.support_contact.phone}</span>
                    </div>
                  )}
                  {equipment.support_contact.company && (
                    <div className="flex items-center gap-2">
                      <span className="text-[var(--text-secondary)]">{equipment.support_contact.company}</span>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </ModalBody>

        <ModalFooter>
          <div className="flex gap-2">
            <Button type="button" variant="secondary" onClick={onClose} disabled={isLoading}>
              {t('common:actions.cancel') || 'Cancel'}
            </Button>
            <Button type="submit" variant="danger" disabled={isLoading}>
              {isLoading ? (
                <>
                  <span className="animate-spin mr-2">🔄</span>
                  {t('common:actions.processing') || 'Processing...'}
                </>
              ) : (
                <>
                  <AlertTriangle className="h-4 w-4 mr-2" />
                  {t('actions.report_failure') || 'Report Failure'}
                </>
              )}
            </Button>
          </div>
        </ModalFooter>
      </form>
    </Modal>
  );
};

// Default export for easier imports
export default ReportFailureModal;