import React, { useEffect, useState } from 'react';
import { Button } from '../components/Button';
import { Card } from '../components/Card';
import { Search, Plus, Trash2, FileText, Download, X, Loader2, Edit2 } from 'lucide-react';
import * as dataSheetService from '../services/dataSheetService';
import type { TechnicalDataSheet } from '../types';
import { format } from 'date-fns';
import { useAuth } from '../context/useAuth';
import { useToast } from '../hooks/useToast';

export const DataSheetLibrary: React.FC = () => {
    const { isGuest, isAdmin } = useAuth();
    const { showGuestWarning } = useToast();
    const [sheets, setSheets] = useState<TechnicalDataSheet[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingId, setEditingId] = useState<string | null>(null);

    // Form State
    const [formData, setFormData] = useState({
        name: '',
        manufacturer: '',
        type: '',
        solidsVolume: '',
        yieldTheoretical: '',
        dftReference: '',
        yieldFactor: '',
        wftMin: '',
        wftMax: '',
        dftMin: '',
        dftMax: '',
        reducer: '',
        mixingRatioWeight: '',
        mixingRatioVolume: '',
        dilution: '',
        notes: '',
        fileUrl: ''
    });
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [uploading, setUploading] = useState(false);
    const [extracting, setExtracting] = useState(false);

    useEffect(() => {
        fetchSheets();
    }, []);

    const fetchSheets = async () => {
        try {
            const response = await dataSheetService.getDataSheets();
            setSheets(response.data);
        } catch (error) {
            console.error('Error fetching sheets', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            const file = e.target.files[0];
            setSelectedFile(file);

            // Auto-extract only for new uploads
            setExtracting(true);
            try {
                const response = await dataSheetService.extractDataSheet(file);
                const data = response.data;
                setFormData(prev => ({
                    ...prev,
                    name: prev.name || data.name || '',
                    manufacturer: prev.manufacturer || data.manufacturer || '',
                    type: prev.type || data.type || '',
                    solidsVolume: data.solidsVolume ? String(data.solidsVolume) : prev.solidsVolume,
                    yieldTheoretical: data.yieldTheoretical ? String(data.yieldTheoretical) : prev.yieldTheoretical,
                    dftReference: data.dftReference ? String(data.dftReference) : prev.dftReference,
                    yieldFactor: data.yieldFactor ? String(data.yieldFactor) : prev.yieldFactor,
                    wftMin: data.wftMin ? String(data.wftMin) : prev.wftMin,
                    wftMax: data.wftMax ? String(data.wftMax) : prev.wftMax,
                    dftMin: data.dftMin ? String(data.dftMin) : prev.dftMin,
                    dftMax: data.dftMax ? String(data.dftMax) : prev.dftMax,
                    reducer: data.reducer || prev.reducer,
                    mixingRatioWeight: data.mixingRatioWeight || prev.mixingRatioWeight,
                    mixingRatioVolume: data.mixingRatioVolume || prev.mixingRatioVolume,
                    fileUrl: data.tempFilePath // Store temporary path
                }));
            } catch (err) {
                console.error('Extraction failed', err);
            } finally {
                setExtracting(false);
            }
        }
    };

    const handleEdit = (sheet: TechnicalDataSheet) => {
        setEditingId(sheet.id);
        setFormData({
            name: sheet.name,
            manufacturer: sheet.manufacturer || '',
            type: sheet.type || '',
            solidsVolume: sheet.solidsVolume ? String(sheet.solidsVolume) : '',
            yieldTheoretical: sheet.yieldTheoretical ? String(sheet.yieldTheoretical) : '',
            dftReference: sheet.dftReference ? String(sheet.dftReference) : '',
            yieldFactor: sheet.yieldFactor ? String(sheet.yieldFactor) : '',
            wftMin: sheet.wftMin ? String(sheet.wftMin) : '',
            wftMax: sheet.wftMax ? String(sheet.wftMax) : '',
            dftMin: sheet.dftMin ? String(sheet.dftMin) : '',
            dftMax: sheet.dftMax ? String(sheet.dftMax) : '',
            reducer: sheet.reducer || '',
            mixingRatioWeight: sheet.mixingRatioWeight || '',
            mixingRatioVolume: sheet.mixingRatioVolume || '',
            dilution: sheet.dilution ? String(sheet.dilution) : '',
            notes: sheet.notes || '',
            fileUrl: sheet.fileUrl || ''
        });
        setSelectedFile(null); // Reset file selection unless user uploads new one
        setIsModalOpen(true);
    };

    const handleOpenModal = () => {
        setEditingId(null);
        setFormData({
            name: '', manufacturer: '', type: '', solidsVolume: '', yieldTheoretical: '',
            dftReference: '', yieldFactor: '', wftMin: '', wftMax: '', dftMin: '', dftMax: '',
            reducer: '', mixingRatioWeight: '', mixingRatioVolume: '', notes: '', fileUrl: '',
            dilution: ''
        });
        setSelectedFile(null);
        setIsModalOpen(true);
    };

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

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

        if (!formData.name) return;

        setUploading(true);
        const data = new FormData();

        if (selectedFile) {
            data.append('file', selectedFile);
        } else if (formData.fileUrl) {
            data.append('fileUrl', formData.fileUrl);
        }

        data.append('name', formData.name);
        data.append('manufacturer', formData.manufacturer);
        data.append('type', formData.type);
        data.append('solidsVolume', formData.solidsVolume);
        data.append('yieldTheoretical', formData.yieldTheoretical);
        data.append('dftReference', formData.dftReference);
        data.append('yieldFactor', formData.yieldFactor);
        data.append('wftMin', formData.wftMin);
        data.append('wftMax', formData.wftMax);
        data.append('dftMin', formData.dftMin);
        data.append('dftMax', formData.dftMax);
        data.append('reducer', formData.reducer);
        data.append('mixingRatioWeight', formData.mixingRatioWeight);
        data.append('mixingRatioVolume', formData.mixingRatioVolume);
        data.append('dilution', formData.dilution);
        data.append('notes', formData.notes);

        try {
            if (editingId) {
                await dataSheetService.updateDataSheet(editingId, data);
            } else {
                if (!selectedFile && !formData.fileUrl) {
                    alert('Selecione um arquivo.');
                    setUploading(false);
                    return;
                }
                await dataSheetService.createDataSheet(data);
            }

            setIsModalOpen(false);
            fetchSheets();
        } catch (error) {
            console.error('Error saving sheet', error);
            alert('Erro ao salvar ficha técnica.');
        } finally {
            setUploading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (isGuest()) {
            showGuestWarning();
            return;
        }

        if (!confirm('Tem certeza que deseja excluir esta ficha?')) return;
        try {
            await dataSheetService.deleteDataSheet(id);
            fetchSheets();
        } catch (error) {
            console.error('Error deleting sheet', error);
        }
    };

    const updateTechnicalData = (field: string, value: string) => {
        const newData = { ...formData, [field]: value };

        // Convert to numbers for calculation
        const solids = field === 'solidsVolume' ? parseFloat(value) : parseFloat(newData.solidsVolume);
        const yieldT = field === 'yieldTheoretical' ? parseFloat(value) : parseFloat(newData.yieldTheoretical);
        const dft = field === 'dftReference' ? parseFloat(value) : parseFloat(newData.dftReference);
        const factor = field === 'yieldFactor' ? parseFloat(value) : parseFloat(newData.yieldFactor);

        if (field === 'solidsVolume' && !isNaN(solids)) {
            // Formula: Factor = Solids * 10
            newData.yieldFactor = (solids * 10).toFixed(2);
            // If we have DFT, update Yield: Yield = Factor / DFT
            if (!isNaN(dft) && dft !== 0) {
                newData.yieldTheoretical = (solids * 10 / dft).toFixed(2);
            }
        } else if (field === 'yieldTheoretical' && !isNaN(yieldT)) {
            // If we have DFT, update Factor: Factor = Yield * DFT
            if (!isNaN(dft)) {
                newData.yieldFactor = (yieldT * dft).toFixed(2);
                newData.solidsVolume = (yieldT * dft / 10).toFixed(1);
            }
        } else if (field === 'dftReference' && !isNaN(dft)) {
            // If we have Factor, update Yield: Yield = Factor / DFT
            if (!isNaN(factor) && dft !== 0) {
                newData.yieldTheoretical = (factor / dft).toFixed(2);
            } else if (!isNaN(solids) && dft !== 0) {
                newData.yieldTheoretical = (solids * 10 / dft).toFixed(2);
            }
        } else if (field === 'yieldFactor' && !isNaN(factor)) {
            newData.solidsVolume = (factor / 10).toFixed(1);
            if (!isNaN(dft) && dft !== 0) {
                newData.yieldTheoretical = (factor / dft).toFixed(2);
            }
        }

        setFormData(newData);
    };

    const filteredSheets = sheets.filter(s =>
        s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        s.manufacturer?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        s.type?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="space-y-10 animate-in fade-in duration-700">
            {/* Page Header */}
            <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 pb-2">
                <div className="space-y-2">
                    <div className="flex items-center gap-4">
                        <div className="w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center text-primary shadow-lg shadow-primary/5">
                            <FileText className="w-8 h-8" />
                        </div>
                        <div>
                            <h1 className="text-3xl md:text-5xl font-black text-text-main tracking-tight mb-0">Biblioteca Técnica</h1>
                            <p className="text-sm text-text-muted font-medium tracking-widest uppercase">Repositório de Fichas de Produto</p>
                        </div>
                    </div>
                </div>

                <div className="flex gap-4">
                    <div className="relative hidden lg:block group">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted group-focus-within:text-primary transition-colors" />
                        <input
                            type="text"
                            placeholder="Buscar tintas ou fabricantes..."
                            className="h-14 w-80 bg-surface border border-border/40 rounded-2xl pl-12 pr-4 text-sm focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all font-medium shadow-sm"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                    {isAdmin() && (
                        <Button onClick={handleOpenModal} size="lg" className="shadow-primary/30 h-14">
                            <Plus className="w-5 h-5 mr-2" />
                            Nova Ficha
                        </Button>
                    )}
                </div>
            </div>

            {/* Mobile/Small Screen Search */}
            <div className="relative lg:hidden">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                <input
                    type="text"
                    placeholder="Buscar..."
                    className="h-12 w-full bg-surface border border-border/40 rounded-xl pl-12 pr-4 text-sm focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all font-medium shadow-sm"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                />
            </div>

            {loading ? (
                <div className="flex flex-col items-center justify-center py-32 space-y-4">
                    <Loader2 size={40} className="text-primary animate-spin" />
                    <p className="text-sm font-bold text-text-muted uppercase tracking-[0.2em]">Carregando Biblioteca...</p>
                </div>
            ) : filteredSheets.length === 0 ? (
                <div className="text-center py-32 bg-surface/50 rounded-[40px] border border-dashed border-border/40">
                    <div className="mx-auto h-24 w-24 bg-surface-soft rounded-full flex items-center justify-center text-text-muted/10 mb-8 border border-border/20">
                        <FileText className="w-12 h-12" />
                    </div>
                    <h3 className="text-2xl font-black text-text-main tracking-tight">Nenhuma ficha disponível</h3>
                    <p className="mt-2 text-text-muted font-medium max-w-sm mx-auto">Sua biblioteca de produtos está vazia. Comece carregando um PDF técnico.</p>
                    {isAdmin() && (
                        <Button
                            variant="secondary"
                            size="md"
                            className="mt-8 border-border/50"
                            onClick={handleOpenModal}
                        >
                            <Plus className="w-4 h-4 mr-2" /> Cadastrar Produto
                        </Button>
                    )}
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-8">
                    {filteredSheets.map((sheet) => (
                        <div key={sheet.id} className="group relative">
                            {/* Card Background Bloom Effect */}
                            <div className="absolute -inset-1 bg-gradient-to-br from-primary/20 via-transparent to-blue-500/10 rounded-[32px] blur-xl opacity-0 group-hover:opacity-100 transition-all duration-700"></div>

                            <Card className="p-0 flex flex-col h-full relative overflow-hidden bg-surface border border-border/40 rounded-[32px] group-hover:border-primary/40 transition-all duration-500 shadow-soft group-hover:shadow-2xl">
                                {/* Header Section */}
                                <div className="p-8 pb-4 relative">
                                    <div className="flex justify-between items-start mb-6">
                                        <div className="flex flex-col gap-2">
                                            <span className="text-[10px] font-black text-primary uppercase tracking-[0.25em]">{sheet.manufacturer || 'FABRICANTE N/D'}</span>
                                            <h3 className="text-2xl font-black text-text-main tracking-tighter leading-none group-hover:text-primary transition-colors" title={sheet.name}>
                                                {sheet.name}
                                            </h3>
                                        </div>
                                        {isAdmin() && (
                                            <div className="flex gap-1 p-1 bg-surface-soft/80 backdrop-blur-md rounded-2xl border border-border/40 opacity-100 md:opacity-0 group-hover:opacity-100 transition-all">
                                                <button
                                                    onClick={() => handleEdit(sheet)}
                                                    className="p-2.5 text-text-muted hover:text-primary transition-all rounded-xl hover:bg-primary/5"
                                                    title="Editar Ficha"
                                                >
                                                    <Edit2 size={16} />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(sheet.id)}
                                                    className="p-2.5 text-text-muted hover:text-error transition-all rounded-xl hover:bg-error/5"
                                                    title="Remover Ficha"
                                                >
                                                    <Trash2 size={16} />
                                                </button>
                                            </div>
                                        )}
                                    </div>

                                    <div className="flex flex-wrap gap-2 mb-4">
                                        <span className="px-3 py-1 bg-primary/10 text-primary text-[9px] font-black uppercase tracking-widest rounded-full border border-primary/20">
                                            {sheet.type || 'S/ TIPO'}
                                        </span>
                                        {sheet.reducer && (
                                            <span className="px-3 py-1 bg-surface-highlight text-text-secondary text-[9px] font-black uppercase tracking-widest rounded-full border border-border/50">
                                                DILUENTE: {sheet.reducer}
                                            </span>
                                        )}
                                    </div>
                                </div>

                                {/* Body Section */}
                                <div className="px-8 space-y-5 flex-1">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="p-4 bg-surface-soft/50 rounded-2xl border border-border/20 flex flex-col">
                                            <span className="text-[9px] text-text-muted font-bold uppercase tracking-wider mb-1">Sólidos por Vol.</span>
                                            <span className="text-xl font-black text-text-main">{sheet.solidsVolume || '0'}%</span>
                                        </div>
                                        <div className="p-4 bg-surface-soft/50 rounded-2xl border border-border/20 flex flex-col">
                                            <span className="text-[9px] text-text-muted font-bold uppercase tracking-wider mb-1">Rend. Teórico</span>
                                            <span className="text-xl font-black text-text-main">{sheet.yieldTheoretical || '0'} <span className="text-[9px] text-text-muted">m²/L</span></span>
                                        </div>
                                    </div>

                                    <div className="p-4 bg-primary/[0.03] border border-primary/10 rounded-2xl">
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-[10px] font-black text-primary/70 uppercase tracking-widest flex items-center gap-2">
                                                <div className="w-1.5 h-1.5 rounded-full bg-primary animate-pulse"></div>
                                                Performance Ref.
                                            </span>
                                            <span className="text-xs font-black text-primary">{sheet.yieldFactor || '0.00'} <span className="text-[8px] font-bold">m².μm/L</span></span>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <span className="text-[9px] font-bold text-text-muted uppercase">EPS de Referência</span>
                                            <span className="text-sm font-bold text-text-main">{sheet.dftReference || '--'} <span className="text-[10px]">μm</span></span>
                                        </div>
                                    </div>

                                    {sheet.mixingRatioVolume && (
                                        <div className="py-1">
                                            <div className="text-[10px] font-bold text-text-muted uppercase tracking-widest border-b border-border/40 pb-2 mb-3">Relação de Mistura (Vol.)</div>
                                            <div className="flex items-center gap-6">
                                                <div className="flex items-baseline gap-1">
                                                    <span className="text-2xl font-black text-text-main">{sheet.mixingRatioVolume.split(':')[0] || '1'}</span>
                                                    <span className="text-[10px] font-bold text-text-muted">PART A</span>
                                                </div>
                                                <div className="h-4 w-[1px] bg-border/40"></div>
                                                <div className="flex items-baseline gap-1">
                                                    <span className="text-2xl font-black text-text-main">{sheet.mixingRatioVolume.split(':')[1] || '1'}</span>
                                                    <span className="text-[10px] font-bold text-text-muted">PART B</span>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {/* Footer Section */}
                                <div className="p-8 pt-6 border-t border-border/40 mt-6 flex items-center justify-between">
                                    <div className="flex flex-col">
                                        <span className="text-[9px] font-black text-text-muted uppercase tracking-tighter">Última Atualização</span>
                                        <span className="text-[11px] font-bold text-text-secondary">{format(new Date(sheet.uploadDate), 'dd MMM, yyyy')}</span>
                                    </div>
                                    {(() => {
                                        if (!sheet.fileUrl) return null;

                                        const fileUrl = sheet.fileUrl.startsWith('http')
                                            ? sheet.fileUrl
                                            : `${dataSheetService.getBaseUrl()}/datasheets/file/${sheet.fileUrl}`;

                                        return (
                                            <a
                                                href={fileUrl}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="flex items-center gap-2.5 h-10 px-6 bg-surface-highlight hover:bg-primary hover:text-white border border-border/40 rounded-xl text-xs font-black transition-all group/btn"
                                            >
                                                <Download size={14} className="group-hover/btn:-translate-y-0.5 transition-transform" />
                                                PDF TÉCNICO
                                            </a>
                                        );
                                    })()}
                                </div>
                            </Card>
                        </div>
                    ))}
                </div>
            )}

            {/* Modal - Reusable for Create and Edit */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-fade-in">
                    <div className="bg-surface rounded-2xl shadow-2xl w-full max-w-lg border border-border/50 flex flex-col max-h-[90vh] overflow-hidden">
                        <div className="p-6 border-b border-border flex justify-between items-center bg-surface">
                            <h2 className="text-xl font-bold text-text-main">
                                {editingId ? 'Editar Ficha Técnica' : 'Nova Ficha Técnica'}
                            </h2>
                            <button
                                onClick={() => setIsModalOpen(false)}
                                className="text-text-muted hover:text-text-main p-1 rounded-lg hover:bg-surface-soft transition-colors"
                                aria-label="Fechar"
                            >
                                <X size={20} />
                            </button>
                        </div>

                        <div className="p-6 overflow-y-auto custom-scrollbar">
                            <form onSubmit={handleSubmit} className="space-y-5">
                                <div className={`p-4 rounded-xl border border-dashed transition-all ${selectedFile ? 'bg-primary/5 border-primary' : 'bg-surface-soft border-border hover:border-primary/50'}`}>
                                    <div className="flex items-center gap-4">
                                        <div className={`p-3 rounded-lg ${extracting ? 'bg-amber-100 text-amber-600' : 'bg-white text-primary shadow-sm'}`}>
                                            {extracting ? <Loader2 size={24} className="animate-spin" /> : <FileText size={24} />}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <label htmlFor="pdf-upload" className="block text-sm font-semibold text-text-main mb-1 cursor-pointer">
                                                {extracting ? 'Analisando documento...' : (editingId ? 'Substituir PDF (Opcional)' : 'Carregar PDF')}
                                            </label>
                                            <input
                                                id="pdf-upload"
                                                type="file"
                                                accept=".pdf"
                                                onChange={handleFileSelect}
                                                className="w-full text-xs text-text-secondary file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark cursor-pointer"
                                                disabled={extracting}
                                            />
                                            <p className="text-xs text-text-muted mt-1 truncate">
                                                {extracting
                                                    ? 'Utilizando OCR se necessário...'
                                                    : (editingId ? 'Mantenha vazio para usar o atual.' : 'Preenchemos os campos automaticamente para você.')}
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div className="space-y-4">
                                    <div>
                                        <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Nome do Produto *</label>
                                        <input
                                            id="product-name"
                                            required
                                            className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                            value={formData.name}
                                            onChange={e => setFormData({ ...formData, name: e.target.value })}
                                            placeholder="Ex: Rezinc Wand 500"
                                            title="Nome do Produto"
                                        />
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Fabricante</label>
                                            <input
                                                id="manufacturer"
                                                className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                value={formData.manufacturer}
                                                onChange={e => setFormData({ ...formData, manufacturer: e.target.value })}
                                                placeholder="Ex: WEG"
                                                title="Fabricante"
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Redutor (Diluente)</label>
                                            <input
                                                id="reducer"
                                                className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                value={formData.reducer}
                                                onChange={e => setFormData({ ...formData, reducer: e.target.value })}
                                                placeholder="Ex: 420.0000"
                                                title="Redutor (Diluente)"
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Tipo de Tinta</label>
                                        <input
                                            id="paint-type"
                                            className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                            value={formData.type}
                                            onChange={e => setFormData({ ...formData, type: e.target.value })}
                                            placeholder="Ex: Epóxi"
                                            title="Tipo de Tinta"
                                        />
                                    </div>
                                </div>

                                <div className="border-t border-border pt-4">
                                    <div className="flex items-center gap-2 mb-3">
                                        <span className="text-xs font-bold text-primary uppercase tracking-wider bg-primary/10 px-2 py-0.5 rounded">Relação de Mistura</span>
                                        <div className="h-px bg-border flex-1"></div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Em Peso (Comp A : B)</label>
                                            <input
                                                id="mixing-ratio-weight"
                                                className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                value={formData.mixingRatioWeight}
                                                onChange={e => setFormData({ ...formData, mixingRatioWeight: e.target.value })}
                                                placeholder="100 : 101"
                                                title="Relação de Mistura em Peso"
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Em Volume (Comp A : B)</label>
                                            <input
                                                id="mixing-ratio-volume"
                                                className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                value={formData.mixingRatioVolume}
                                                onChange={e => setFormData({ ...formData, mixingRatioVolume: e.target.value })}
                                                placeholder="1 : 1"
                                                title="Relação de Mistura em Volume"
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="border-t border-border pt-4">
                                    <div className="flex items-center gap-2 mb-3">
                                        <span className="text-xs font-bold text-primary uppercase tracking-wider bg-primary/10 px-2 py-0.5 rounded">Dados Técnicos</span>
                                        <div className="h-px bg-border flex-1"></div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="col-span-2 grid grid-cols-2 gap-4 p-3 bg-surface-soft rounded-xl border border-border/50">
                                            <div className="col-span-2 text-[10px] font-bold text-text-muted uppercase mb-1">Intervalos de Aplicação</div>
                                            <div>
                                                <label className="block text-[10px] font-medium text-text-secondary mb-1">Úmida (WFT µm)</label>
                                                <div className="flex items-center gap-1">
                                                    <input type="number" className="w-full p-1.5 text-xs rounded border border-border bg-surface" value={formData.wftMin} onChange={e => setFormData({ ...formData, wftMin: e.target.value })} placeholder="Min" />
                                                    <span className="text-xs text-text-muted">/</span>
                                                    <input type="number" className="w-full p-1.5 text-xs rounded border border-border bg-surface" value={formData.wftMax} onChange={e => setFormData({ ...formData, wftMax: e.target.value })} placeholder="Max" />
                                                </div>
                                            </div>
                                            <div>
                                                <label className="block text-[10px] font-medium text-text-secondary mb-1">Seca (DFT µm)</label>
                                                <div className="flex items-center gap-1">
                                                    <input type="number" className="w-full p-1.5 text-xs rounded border border-border bg-surface" value={formData.dftMin} onChange={e => setFormData({ ...formData, dftMin: e.target.value })} placeholder="Min" />
                                                    <span className="text-xs text-text-muted">/</span>
                                                    <input type="number" className="w-full p-1.5 text-xs rounded border border-border bg-surface" value={formData.dftMax} onChange={e => setFormData({ ...formData, dftMax: e.target.value })} placeholder="Max" />
                                                </div>
                                            </div>
                                        </div>

                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Vol. Sólidos (%)</label>
                                            <div className="relative">
                                                <input
                                                    id="solids-volume"
                                                    type="number" step="0.1"
                                                    className="w-full p-2.5 pl-3 pr-8 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                    value={formData.solidsVolume}
                                                    onChange={e => updateTechnicalData('solidsVolume', e.target.value)}
                                                    placeholder="0"
                                                    title="Volume de Sólidos (%)"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted text-sm">%</span>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Espessura Ref. (DFT)</label>
                                            <div className="relative">
                                                <input
                                                    id="dft-reference"
                                                    type="number" step="1"
                                                    className="w-full p-2.5 pl-3 pr-10 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                    value={formData.dftReference}
                                                    onChange={e => updateTechnicalData('dftReference', e.target.value)}
                                                    placeholder="0"
                                                    title="Espessura Referência (DFT)"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted text-sm">µm</span>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Rendimento Teórico</label>
                                            <div className="relative">
                                                <input
                                                    id="yield-theoretical"
                                                    type="number" step="0.01"
                                                    className="w-full p-2.5 pl-3 pr-10 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                    value={formData.yieldTheoretical}
                                                    onChange={e => updateTechnicalData('yieldTheoretical', e.target.value)}
                                                    placeholder="0.00"
                                                    title="Rendimento Teórico"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted text-sm">m²/L</span>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Fator de Rendimento</label>
                                            <div className="relative">
                                                <input
                                                    id="yield-factor"
                                                    type="number" step="0.1"
                                                    className="w-full p-2.5 pl-3 pr-16 rounded-lg border-2 border-primary/30 bg-primary/5 focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all font-bold"
                                                    value={formData.yieldFactor}
                                                    onChange={e => updateTechnicalData('yieldFactor', e.target.value)}
                                                    placeholder="0.0"
                                                    title="Fator de Rendimento"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-primary/70 text-[10px] font-bold leading-tight text-right w-12">m².µm/L</span>
                                            </div>
                                        </div>

                                        <div>
                                            <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Diluição Recomendada (%)</label>
                                            <div className="relative">
                                                <input
                                                    id="dilution"
                                                    type="number"
                                                    className="w-full p-2.5 rounded-lg border border-border bg-surface focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
                                                    value={formData.dilution}
                                                    onChange={e => setFormData({ ...formData, dilution: e.target.value })}
                                                    placeholder="0"
                                                    title="Diluição Recomendada (%)"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted text-sm">%</span>
                                            </div>
                                        </div>
                                    </div>
                                    <p className="mt-2 text-[10px] text-text-muted italic">
                                        * O Fator de Rendimento representa a área coberta por 1L para 1µm de espessura (Sólidos % × 10).
                                    </p>
                                </div>

                                <div className="pt-6 flex justify-end gap-3 border-t border-border mt-2">
                                    <Button type="button" variant="ghost" onClick={() => setIsModalOpen(false)}>Cancelar</Button>
                                    <Button type="submit" disabled={uploading}>
                                        {uploading ? (editingId ? 'Salvando...' : 'Enviando...') : (editingId ? 'Salvar Alterações' : 'Criar Ficha')}
                                    </Button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};
