import React, { useState, useEffect } from 'react';
import { Modal } from '../Modal';
import { Input } from '../Input';
import { Button } from '../Button';
import { Select } from '../Select';
import { PaintingInspectionForm } from '../forms/PaintingInspectionForm';
import { SurfaceTreatmentForm } from '../forms/SurfaceTreatmentForm';
import { PhotoUpload } from '../PhotoUpload';
import api from '../../services/api';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';
import type { Inspection, ApplicationRecord } from '../../types';
import { Paintbrush, Hammer } from 'lucide-react';
import { clsx } from 'clsx';
import { stockService } from '../../services/stockService';
import type { IInstrument } from '../../types/Instrument';

interface CreateInspectionModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    projectId?: string;
    initialData?: Inspection;
    availableBatches?: ApplicationRecord[];
    existingInspections?: Inspection[];
}

interface InspectionFormData {
    date: string;
    inspector: string;
    pieceDescription: string;
    appearance: string;
    defects: string;
    photos: string[];
    applicationRecordId: string;
    partTemperature: string;
    weightKg: string;
    instrumentId: string;

    // Painting
    epsPoints: string[];
    adhesionTest: string;
    stockItemId: string;

    // Surface Treatment
    batch: string;
    treatmentExecutor: string;
    treatmentType: string;
    cleaningDegree: string;
    roughnessReadings: string[];
    flashRust: string;
    temperature: string;
    relativeHumidity: string;
    period: string;
}

const EMPTY_BATCHES: ApplicationRecord[] = [];
const EMPTY_INSPECTIONS: Inspection[] = [];

export const CreateInspectionModal: React.FC<CreateInspectionModalProps> = ({
    isOpen, onClose, onSuccess, projectId, initialData, availableBatches = EMPTY_BATCHES, existingInspections = EMPTY_INSPECTIONS
}) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);
    const [projects, setProjects] = useState<{ id: string, name: string }[]>([]);
    const [selectedProjectId, setSelectedProjectId] = useState(projectId || '');
    const [stockItems, setStockItems] = useState<{ _id: string, rrNumber: string, batchNumber: string, quantity: number, unit: string }[]>([]);
    const [instruments, setInstruments] = useState<IInstrument[]>([]);

    useEffect(() => {
        stockService.getAll().then(data => setStockItems(data));
        api.get('/instruments').then(res => setInstruments(res.data.filter((i: IInstrument) => i.status === 'active')));
    }, []);

    const [type, setType] = useState<'painting' | 'surface_treatment'>('painting');

    const [formData, setFormData] = useState<InspectionFormData>({
        date: '',
        inspector: '',
        pieceDescription: '',
        appearance: '',
        defects: '',
        photos: [],
        applicationRecordId: '',
        partTemperature: '',
        weightKg: '',
        instrumentId: '',

        // Painting
        epsPoints: Array(20).fill(''),
        adhesionTest: '',
        stockItemId: '',

        // Surface Treatment
        batch: '',
        treatmentExecutor: '',
        treatmentType: '',
        cleaningDegree: '',
        roughnessReadings: Array(5).fill(''),
        flashRust: '',
        temperature: '',
        relativeHumidity: '',
        period: ''
    });

    useEffect(() => {
        if (!projectId) {
            api.get('/projects').then(response => {
                setProjects(response.data);
            }).catch(err => console.error("Error loading projects", err));
        } else {
            setSelectedProjectId(projectId);
        }
    }, [projectId, isOpen]);

    useEffect(() => {
        if (initialData) {
            const initialEps = Array(20).fill('');
            if (initialData.epsPoints) {
                initialData.epsPoints.forEach((p, i) => { if (i < 20) initialEps[i] = p?.toString() || ''; });
            }

            const initialRoughness = Array(5).fill('');
            if (initialData.roughnessReadings) {
                initialData.roughnessReadings.forEach((p, i) => { if (i < 5) initialRoughness[i] = p?.toString() || ''; });
            }

            setType(initialData.type || 'painting');
            setFormData({
                date: initialData.date ? new Date(initialData.date).toISOString().split('T')[0] : '',
                inspector: initialData.inspector || '',
                pieceDescription: initialData.pieceDescription || '',
                appearance: initialData.appearance || '',
                defects: initialData.defects || '',
                photos: initialData.photos || [],
                applicationRecordId: initialData.applicationRecordId || '',

                epsPoints: initialEps,
                adhesionTest: initialData.adhesionTest || '',
                stockItemId: typeof initialData.stockItemId === 'object' ? initialData.stockItemId._id : (initialData.stockItemId || ''),

                batch: initialData.batch || '',
                treatmentExecutor: initialData.treatmentExecutor || '',
                treatmentType: initialData.treatmentType || '',
                cleaningDegree: initialData.cleaningDegree || '',
                roughnessReadings: initialRoughness,
                flashRust: initialData.flashRust || '',
                temperature: initialData.temperature?.toString() || '',
                relativeHumidity: initialData.relativeHumidity?.toString() || '',
                period: initialData.period || '',
                partTemperature: initialData.partTemperature?.toString() || '',
                weightKg: initialData.weightKg?.toString() || '',
                instrumentId: typeof initialData.instrumentId === 'object' && initialData.instrumentId ? (initialData.instrumentId as IInstrument)._id : (initialData.instrumentId as string || '')
            });

            if (initialData.projectId) setSelectedProjectId(initialData.projectId);
        } else {
            // Auto-calculate next batch number logic
            let nextBatch = '';
            if (existingInspections && existingInspections.length > 0) {
                const nums = existingInspections
                    .map(i => {
                        const match = (i.batch || '').match(/Lote-(\d+)/i);
                        return match ? parseInt(match[1]) : 0;
                    })
                    .filter(n => n > 0);

                const maxNum = nums.length > 0 ? Math.max(...nums) : 0;
                nextBatch = `Lote-${String(maxNum + 1).padStart(2, '0')}`;
            } else {
                nextBatch = 'Lote-01';
            }

            // Reset form
            setType('painting');
            setFormData({
                date: new Date().toISOString().split('T')[0],
                inspector: '',
                pieceDescription: '',
                appearance: '',
                defects: '',
                photos: [],
                applicationRecordId: '',
                epsPoints: Array(20).fill(''),
                adhesionTest: '',
                stockItemId: '',
                batch: nextBatch, // Auto-filled
                treatmentExecutor: '',
                treatmentType: '',
                cleaningDegree: '',
                roughnessReadings: Array(5).fill(''),
                flashRust: '',
                temperature: '',
                relativeHumidity: '',
                period: '',
                partTemperature: '',
                weightKg: '',
                instrumentId: ''
            });
            if (projectId) setSelectedProjectId(projectId);
        }
        // eslint-disable-next-line
    }, [initialData, isOpen, projectId]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleEpsChange = (index: number, value: string) => {
        const newPoints = [...formData.epsPoints];
        newPoints[index] = value;
        setFormData({ ...formData, epsPoints: newPoints });
    };

    const handleRoughnessChange = (index: number, value: string) => {
        const newPoints = [...formData.roughnessReadings];
        newPoints[index] = value;
        setFormData({ ...formData, roughnessReadings: newPoints });
    };

    const handlePhotoAdd = (url: string) => {
        setFormData((prev) => ({ ...prev, photos: [...prev.photos, url] }));
    };

    const handlePhotoRemove = (index: number) => {
        setFormData((prev) => ({ ...prev, photos: prev.photos.filter((_, i) => i !== index) }));
    };

    // Validation
    const numericEps = formData.epsPoints.map(p => parseFloat(p)).filter(p => !isNaN(p));
    // const isValidPainting = type === 'painting' && numericEps.length >= 10; // Relaxed
    // const isValidTreatment = type === 'surface_treatment' && formData.treatmentType && formData.cleaningDegree; // Relaxed

    // Basic validation
    const canSubmit = formData.date && formData.inspector && formData.pieceDescription;

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (isGuest()) {
            showGuestWarning();
            return;
        }

        if (!selectedProjectId) {
            alert("Selecione um projeto");
            return;
        }

        setLoading(true);
        try {
            const payload = {
                projectId: selectedProjectId,
                type,
                date: formData.date,
                inspector: formData.inspector,
                pieceDescription: formData.pieceDescription,
                appearance: formData.appearance,
                defects: formData.defects,
                photos: formData.photos,
                applicationRecordId: formData.applicationRecordId || null,

                // Fields are sent regardless, backend optionality handles it
                epsPoints: formData.epsPoints.map(p => p !== '' ? parseFloat(p) : null),
                adhesionTest: formData.adhesionTest,
                stockItemId: formData.stockItemId || null,

                batch: formData.batch,
                treatmentExecutor: formData.treatmentExecutor,
                treatmentType: formData.treatmentType,
                cleaningDegree: formData.cleaningDegree,
                roughnessReadings: formData.roughnessReadings.map(p => p !== '' ? parseFloat(p) : null),
                flashRust: formData.flashRust,
                temperature: formData.temperature ? parseFloat(formData.temperature) : null,
                relativeHumidity: formData.relativeHumidity ? parseFloat(formData.relativeHumidity) : null,
                period: formData.period,
                partTemperature: formData.partTemperature ? parseFloat(formData.partTemperature) : null,
                weightKg: formData.weightKg ? parseFloat(formData.weightKg) : null,
                instrumentId: formData.instrumentId || null
            };

            if (initialData) {
                await api.put(`/inspections/${initialData.id}`, payload);
            } else {
                await api.post('/inspections', payload);
            }

            onSuccess();
            onClose();
        } catch (error) {
            console.error('Error saving inspection', error);
            alert('Erro ao salvar inspeção');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal isOpen={isOpen} onClose={onClose} title={initialData ? "Editar Inspeção" : "Nova Inspeção"}>
            <form onSubmit={handleSubmit} className="space-y-6">

                {/* Tabs */}
                <div className="flex p-1 bg-surface-soft rounded-xl border border-border/40 mb-6">
                    <button
                        type="button"
                        onClick={() => setType('surface_treatment')}
                        className={clsx(
                            "flex-1 flex items-center justify-center gap-2 py-2.5 text-sm font-bold rounded-lg transition-all",
                            type === 'surface_treatment'
                                ? "bg-amber-600 text-white shadow-lg shadow-amber-600/20"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <Hammer size={16} />
                        Tratamento
                    </button>
                    <button
                        type="button"
                        onClick={() => setType('painting')}
                        className={clsx(
                            "flex-1 flex items-center justify-center gap-2 py-2.5 text-sm font-bold rounded-lg transition-all",
                            type === 'painting'
                                ? "bg-primary text-white shadow-lg shadow-primary/20"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <Paintbrush size={16} />
                        Pintura
                    </button>
                </div>

                {/* Common Fields */}
                <div className="space-y-4">
                    {!projectId && (
                        <Select
                            name="projectId"
                            label="Projeto"
                            options={projects.map(p => ({ label: p.name, value: p.id }))}
                            value={selectedProjectId}
                            onChange={(e) => setSelectedProjectId(e.target.value)}
                            required
                        />
                    )}

                    {/* Batch Selection (Painting Only) */}
                    {type === 'painting' && availableBatches.length > 0 && (
                        <Select
                            name="applicationRecordId"
                            label="Vincular ao Lote de Pintura (Opcional)"
                            options={[
                                { label: 'Selecione um lote...', value: '' },
                                ...availableBatches.map(b => ({
                                    label: `${b.pieceDescription || 'Lote sem nome'} (${b.coatStage})`,
                                    value: b.id
                                }))
                            ]}
                            value={formData.applicationRecordId}
                            onChange={handleChange}
                        />
                    )}

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <Input name="date" label="Data da Inspeção" type="date" value={formData.date} onChange={handleChange} required />
                        <Input name="inspector" label="Inspetor" value={formData.inspector} onChange={handleChange} required />
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <Input name="pieceDescription" label="Peça/Área Inspecionada" value={formData.pieceDescription} onChange={handleChange} required />
                        <Input name="weightKg" label="Peso Inspecionado (kg)" type="number" value={formData.weightKg} onChange={handleChange} required placeholder="Ex: 688" />
                    </div>

                    <Select
                        name="instrumentId"
                        label="Instrumento Utilizado"
                        options={[
                            { label: 'Selecione um instrumento...', value: '' },
                            ...instruments.map(i => ({ label: `${i.name} - ${i.serialNumber} (${i.type})`, value: i._id }))
                        ]}
                        value={formData.instrumentId}
                        onChange={handleChange}
                    />
                </div>

                {/* Specific Forms */}
                {type === 'painting' ? (
                    <PaintingInspectionForm
                        formData={formData}
                        handleChange={handleChange}
                        handleEpsChange={handleEpsChange}
                        numericPoints={numericEps}
                        stockItems={stockItems}
                        handleRoughnessChange={handleRoughnessChange}
                    />
                ) : (
                    <SurfaceTreatmentForm
                        formData={formData}
                        handleChange={handleChange}
                        handleReadingChange={handleRoughnessChange}
                    />
                )}

                {/* Common Footer (Photos, Observation, Status) */}
                <div className="space-y-4 pt-4 border-t border-border/40">
                    <PhotoUpload
                        photos={formData.photos}
                        onPhotosChange={handlePhotoAdd}
                        onRemovePhoto={handlePhotoRemove}
                    />

                    <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Defeitos / Observações</label>
                        <textarea
                            name="defects"
                            className="flex min-h-[80px] w-full rounded-xl border border-border bg-[var(--input-bg)] text-[var(--input-text)] px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary disabled:opacity-50 transition-all placeholder:text-text-muted/50"
                            value={formData.defects}
                            onChange={handleChange}
                            placeholder="Descreva observações, falhas encontradas ou detalhes adicionais..."
                        />
                    </div>

                    <Select
                        name="appearance"
                        label="Resultado Final"
                        options={[
                            { label: 'Aprovada', value: 'approved' },
                            { label: 'Reprovada', value: 'rejected' },
                            { label: 'Com Ressalvas', value: 'notes' }
                        ]}
                        value={formData.appearance}
                        onChange={handleChange}
                        required
                    />
                </div>

                <div className="flex justify-end gap-2 mt-6">
                    <Button type="button" variant="ghost" onClick={onClose} disabled={loading}>Cancelar</Button>
                    <Button type="submit" disabled={loading || !canSubmit}>
                        {loading ? 'Salvando...' : (initialData ? 'Salvar Alterações' : 'Registrar Inspeção')}
                    </Button>
                </div>
            </form>
        </Modal>
    );
};
