import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CheckCircle, Clock, FileText, HelpCircle, User, Wrench } 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 MarkAsRepairedModalProps {
  isOpen: boolean;
  onClose: () => void;
  equipment: Equipment;
  onMarkAsRepaired: (repairData: {
    repairDate: string;
    technicianName: string;
    repairDescription: string;
    partsReplaced: string[];
    cost: number;
    photos?: File[];
    testResults: boolean;
  }) => Promise<void>;
  isLoading?: boolean;
}

export const MarkAsRepairedModal: React.FC<MarkAsRepairedModalProps> = ({
  isOpen,
  onClose,
  equipment,
  onMarkAsRepaired,
  isLoading = false
}) => {
  const { t } = useTranslation(['equipment', 'common']);
  const { showToast } = useToast();
  
  const [repairDate, setRepairDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [technicianName, setTechnicianName] = useState<string>('');
  const [repairDescription, setRepairDescription] = useState<string>('');
  const [partsReplaced, setPartsReplaced] = useState<string[]>([]);
  const [newPart, setNewPart] = useState<string>('');
  const [cost, setCost] = useState<number>(0);
  const [photos, setPhotos] = useState<File[]>([]);
  const [testResults, setTestResults] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

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

    if (!technicianName.trim()) {
      setError(t('errors.technician_required') || 'Technician name is required');
      return;
    }

    try {
      await onMarkAsRepaired({
        repairDate,
        technicianName,
        repairDescription,
        partsReplaced,
        cost,
        photos,
        testResults
      });
      
      showToast({
        title: t('success.repair_completed') || 'Repair Completed',
        message: t('success.repair_completed_message', { equipment: equipment.name }) || `${equipment.name} has been marked as repaired successfully`,
        type: 'success'
      });
      
      // Reset form
      setRepairDescription('');
      setTechnicianName('');
      setPartsReplaced([]);
      setNewPart('');
      setCost(0);
      setPhotos([]);
      setTestResults(true);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : t('errors.repair_failed') || 'Failed to mark as repaired');
      showToast({
        title: t('errors.repair_failed') || 'Repair Failed',
        message: err instanceof Error ? err.message : t('errors.try_again') || 'Please try again',
        type: 'error'
      });
    }
  };

  const handleAddPart = () => {
    if (newPart.trim() && !partsReplaced.includes(newPart.trim())) {
      setPartsReplaced([...partsReplaced, newPart.trim()]);
      setNewPart('');
    }
  };

  const handleRemovePart = (part: string) => {
    setPartsReplaced(partsReplaced.filter(p => p !== part));
  };

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

  // Calculate downtime
  const calculateDowntime = () => {
    if (!equipment.lastMaintenance) return 0;
    
    const lastMaintenanceDate = new Date(equipment.lastMaintenance);
    const repairDateObj = new Date(repairDate);
    
    const diffHours = Math.abs(repairDateObj.getTime() - lastMaintenanceDate.getTime()) / (1000 * 60 * 60);
    return Math.round(diffHours);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="lg">
      <form onSubmit={handleSubmit}>
        <ModalHeader>
          <div className="flex items-center gap-2">
            <CheckCircle className="text-green-500" />
            <h3 className="text-lg font-semibold text-[var(--text-primary)]">
              {t('mark_repaired.title', { equipment: equipment.name }) || `Mark as Repaired: ${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">
                <Wrench 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>

            {/* Repair Date */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.repair_date') || 'Repair Date'}
              </label>
              <Input
                type="date"
                value={repairDate}
                onChange={(e) => setRepairDate(e.target.value)}
                required
              />
            </div>

            {/* Technician Name */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.technician_name') || 'Technician Name'}
              </label>
              <Input
                value={technicianName}
                onChange={(e) => setTechnicianName(e.target.value)}
                placeholder={t('placeholders.technician_name') || 'Enter technician name'}
                required
              />
            </div>

            {/* Repair Description */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.repair_description') || 'Repair Description'}
              </label>
              <Textarea
                value={repairDescription}
                onChange={(e) => setRepairDescription(e.target.value)}
                placeholder={t('placeholders.repair_description') || 'Describe the repair work performed...'}
                rows={4}
                required
              />
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('hints.repair_description') || 'Include what was fixed, methods used, and any observations'}
              </p>
            </div>

            {/* Parts Replaced */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.parts_replaced') || 'Parts Replaced'}
              </label>
              <div className="flex gap-2 mb-2">
                <Input
                  value={newPart}
                  onChange={(e) => setNewPart(e.target.value)}
                  placeholder={t('placeholders.add_part') || 'Add part name'}
                />
                <Button type="button" size="sm" onClick={handleAddPart} disabled={!newPart.trim()}>
                  {t('actions.add') || 'Add'}
                </Button>
              </div>
              {partsReplaced.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {partsReplaced.map((part, index) => (
                    <div key={index} className="bg-[var(--background-tertiary)] px-3 py-1 rounded-full text-sm flex items-center gap-2">
                      <span>{part}</span>
                      <button
                        type="button"
                        onClick={() => handleRemovePart(part)}
                        className="text-red-500 hover:text-red-700"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Cost */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('fields.cost') || 'Repair Cost (€)'}
              </label>
              <Input
                type="number"
                value={cost}
                onChange={(e) => setCost(parseFloat(e.target.value) || 0)}
                min={0}
                step={0.01}
                placeholder="0.00"
              />
            </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.repair_photos') || 'Upload before/after photos of the repair (max 5MB each)'}
              </p>
            </div>

            {/* Test Results */}
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="testResults"
                checked={testResults}
                onChange={(e) => setTestResults(e.target.checked)}
                className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                required
              />
              <label htmlFor="testResults" className="text-sm text-[var(--text-primary)]">
                {t('fields.test_results') || 'Equipment tested and operational'}
              </label>
              <HelpCircle className="h-4 w-4 text-[var(--text-secondary)]" />
            </div>

            {/* Downtime Summary */}
            <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">
                <Clock className="h-4 w-4" />
                {t('downtime_summary.title') || 'Downtime Summary'}
              </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('downtime_summary.downtime') || 'Downtime'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">{calculateDowntime()} {t('downtime_summary.hours') || 'hours'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[var(--text-secondary)]">{t('downtime_summary.cost') || 'Estimated Cost'}:</span>
                  <span className="font-medium text-[var(--text-primary)]">€{cost.toFixed(2)}</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="success" disabled={isLoading}>
              {isLoading ? (
                <>
                  <span className="animate-spin mr-2">🔄</span>
                  {t('common:actions.processing') || 'Processing...'}
                </>
              ) : (
                <>
                  <CheckCircle className="h-4 w-4 mr-2" />
                  {t('actions.mark_repaired') || 'Mark as Repaired'}
                </>
              )}
            </Button>
          </div>
        </ModalFooter>
      </form>
    </Modal>
  );
};

// Default export for easier imports
export default MarkAsRepairedModal;