import React, { useState, useRef } from 'react';
import { X, Upload, AlertCircle, Loader, CheckCircle, FileSpreadsheet } from 'lucide-react';
import * as XLSX from 'xlsx';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
const TEAL = '#14B8A6';
const RED = '#EF4444';
const AMBER = '#F59E0B';
const EMERALD = '#10B981';

function mapColumnHeaders(headers) {
    const mapping = {};
    for (const h of headers) {
        const lower = h.toLowerCase().trim();
        if (lower === 'hostname') mapping.hostname = h;
        else if (lower === 'resolution date' || lower === 'resolution_date') mapping.resolution_date = h;
        else if (lower === 'remediation plan' || lower === 'remediation_plan') mapping.remediation_plan = h;
        else if (lower === 'notes') mapping.notes = h;
    }
    return mapping;
}

function isValidDateString(str) {
    if (!str || typeof str !== 'string' || str.trim() === '') return false;
    const d = new Date(str);
    if (isNaN(d.getTime())) return false;
    // Check it's a real date by comparing parts
    const parts = str.trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (!parts) return false;
    const [, y, m, day] = parts;
    return d.getFullYear() === parseInt(y) && (d.getMonth() + 1) === parseInt(m) && d.getDate() === parseInt(day);
}

export default function BulkUploadModal({ onClose }) {
    const fileRef = useRef(null);
    const [step, setStep] = useState('upload'); // upload, preview, committing, done
    const [parsedRows, setParsedRows] = useState([]);
    const [preview, setPreview] = useState(null);
    const [previewLoading, setPreviewLoading] = useState(false);
    const [commitLoading, setCommitLoading] = useState(false);
    const [error, setError] = useState(null);
    const [commitResult, setCommitResult] = useState(null);

    const handleFileSelect = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        setError(null);

        try {
            const data = await file.arrayBuffer();
            const workbook = XLSX.read(data, { type: 'array' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(sheet, { defval: '' });

            if (jsonData.length === 0) {
                setError('File contains no data rows');
                return;
            }

            const headers = Object.keys(jsonData[0]);
            const colMap = mapColumnHeaders(headers);

            if (!colMap.hostname) {
                setError('File must contain a Hostname column');
                return;
            }

            const hasUpdatableFields = colMap.resolution_date || colMap.remediation_plan || colMap.notes;
            if (!hasUpdatableFields) {
                setError('No updatable fields found (need Resolution Date, Remediation Plan, or Notes)');
                return;
            }

            // Build rows for API
            const rows = jsonData.map(row => {
                const mapped = { hostname: String(row[colMap.hostname] || '').trim() };
                if (colMap.resolution_date) {
                    const val = String(row[colMap.resolution_date] || '').trim();
                    mapped.resolution_date = val || null;
                }
                if (colMap.remediation_plan) {
                    const val = String(row[colMap.remediation_plan] || '').trim();
                    mapped.remediation_plan = val || null;
                }
                if (colMap.notes) {
                    const val = String(row[colMap.notes] || '').trim();
                    mapped.notes = val || null;
                }
                return mapped;
            }).filter(r => r.hostname);

            // Client-side validation
            const validatedRows = rows.map(row => {
                const errors = [];
                if (row.resolution_date && !isValidDateString(row.resolution_date)) {
                    errors.push('Invalid date format for Resolution Date');
                }
                if (row.remediation_plan && row.remediation_plan.length > 2000) {
                    errors.push('Remediation Plan exceeds 2000 characters');
                }
                return { ...row, _clientErrors: errors };
            });

            setParsedRows(validatedRows);

            // Call bulk-preview API
            setPreviewLoading(true);
            setStep('preview');

            const res = await fetch(`${API_BASE}/compliance/vcl/bulk-preview`, {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ rows: validatedRows.map(({ _clientErrors, ...r }) => r) }),
            });
            const previewData = await res.json();
            if (!res.ok) throw new Error(previewData.error || 'Preview failed');

            setPreview(previewData);
        } catch (err) {
            setError(err.message);
            setStep('upload');
        } finally {
            setPreviewLoading(false);
        }
    };

    const handleCommit = async () => {
        if (!preview || !preview.details) return;

        setCommitLoading(true);
        setError(null);

        try {
            const changes = preview.details
                .filter(d => d.status === 'changed')
                .map(d => {
                    const change = { hostname: d.hostname };
                    if (d.fields.resolution_date) change.resolution_date = d.fields.resolution_date.new;
                    if (d.fields.remediation_plan) change.remediation_plan = d.fields.remediation_plan.new;
                    if (d.fields.notes) change.notes = d.fields.notes.new;
                    return change;
                });

            const res = await fetch(`${API_BASE}/compliance/vcl/bulk-commit`, {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ changes }),
            });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Commit failed');

            setCommitResult(data);
            setStep('done');
        } catch (err) {
            setError(err.message);
        } finally {
            setCommitLoading(false);
        }
    };

    const handleCancel = () => {
        setParsedRows([]);
        setPreview(null);
        setError(null);
        onClose();
    };

    return (
        <>
            {/* Backdrop */}
            <div onClick={handleCancel} style={{
                position: 'fixed', inset: 0, background: 'rgba(10,14,39,0.92)',
                backdropFilter: 'blur(6px)', zIndex: 60,
            }} />

            {/* Modal */}
            <div style={{
                position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
                width: '90%', maxWidth: '720px', maxHeight: '85vh',
                background: 'linear-gradient(135deg, rgba(30,41,59,0.99) 0%, rgba(15,23,42,1) 100%)',
                border: `1px solid ${TEAL}30`,
                borderRadius: '0.75rem',
                boxShadow: '0 20px 60px rgba(0,0,0,0.7)',
                zIndex: 61,
                display: 'flex', flexDirection: 'column',
                overflow: 'hidden',
            }}>
                {/* Header */}
                <div style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '1.25rem 1.5rem',
                    borderBottom: '1px solid rgba(255,255,255,0.06)',
                    flexShrink: 0,
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                        <FileSpreadsheet style={{ width: '18px', height: '18px', color: TEAL }} />
                        <span style={{ fontFamily: 'monospace', fontSize: '0.9rem', fontWeight: '700', color: '#E2E8F0', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                            Bulk Upload
                        </span>
                    </div>
                    <button onClick={handleCancel} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#475569', padding: '0.25rem' }}
                        onMouseEnter={e => e.currentTarget.style.color = '#E2E8F0'}
                        onMouseLeave={e => e.currentTarget.style.color = '#475569'}>
                        <X style={{ width: '18px', height: '18px' }} />
                    </button>
                </div>

                {/* Body */}
                <div style={{ flex: 1, overflowY: 'auto', padding: '1.5rem' }}>
                    {/* Error display */}
                    {error && (
                        <div style={{
                            display: 'flex', alignItems: 'center', gap: '0.5rem',
                            padding: '0.75rem 1rem', marginBottom: '1rem',
                            background: 'rgba(239,68,68,0.08)',
                            border: '1px solid rgba(239,68,68,0.3)',
                            borderRadius: '0.375rem',
                            color: '#F87171', fontSize: '0.8rem', fontFamily: 'monospace',
                        }}>
                            <AlertCircle style={{ width: '16px', height: '16px', flexShrink: 0 }} />
                            {error}
                        </div>
                    )}

                    {/* Step: Upload */}
                    {step === 'upload' && (
                        <div style={{ textAlign: 'center', padding: '2rem 0' }}>
                            <div style={{
                                border: '2px dashed rgba(20,184,166,0.3)',
                                borderRadius: '0.75rem',
                                padding: '3rem 2rem',
                                cursor: 'pointer',
                                transition: 'all 0.15s',
                            }}
                                onClick={() => fileRef.current?.click()}
                                onMouseEnter={e => e.currentTarget.style.borderColor = TEAL}
                                onMouseLeave={e => e.currentTarget.style.borderColor = 'rgba(20,184,166,0.3)'}
                            >
                                <Upload style={{ width: '32px', height: '32px', color: TEAL, margin: '0 auto 1rem' }} />
                                <div style={{ fontFamily: 'monospace', fontSize: '0.85rem', color: '#CBD5E1', marginBottom: '0.5rem' }}>
                                    Click to select an .xlsx file
                                </div>
                                <div style={{ fontSize: '0.72rem', color: '#475569', fontFamily: 'monospace' }}>
                                    Columns: Hostname (required), Resolution Date, Remediation Plan, Notes
                                </div>
                            </div>
                            <input
                                ref={fileRef}
                                type="file"
                                accept=".xlsx"
                                onChange={handleFileSelect}
                                style={{ display: 'none' }}
                            />
                        </div>
                    )}

                    {/* Step: Preview loading */}
                    {step === 'preview' && previewLoading && (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '3rem' }}>
                            <Loader style={{ width: '28px', height: '28px', color: TEAL, animation: 'spin 1s linear infinite' }} />
                            <span style={{ marginLeft: '0.75rem', fontFamily: 'monospace', fontSize: '0.8rem', color: '#94A3B8' }}>
                                Analyzing changes…
                            </span>
                        </div>
                    )}

                    {/* Step: Preview results */}
                    {step === 'preview' && !previewLoading && preview && (
                        <div>
                            {/* Summary counts */}
                            <div style={{ display: 'flex', gap: '1rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
                                <SummaryBadge label="Matched" value={preview.matched} color={EMERALD} />
                                <SummaryBadge label="Unmatched" value={preview.unmatched} color={AMBER} />
                                <SummaryBadge label="Changes" value={preview.changes} color={TEAL} />
                                <SummaryBadge label="Invalid" value={preview.invalid} color={RED} />
                            </div>

                            {/* Changed rows */}
                            {preview.details && preview.details.filter(d => d.status === 'changed').length > 0 && (
                                <div style={{ marginBottom: '1.25rem' }}>
                                    <div style={{ fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.08em', color: '#475569', marginBottom: '0.5rem' }}>
                                        Changed Rows
                                    </div>
                                    <div style={{ maxHeight: '200px', overflowY: 'auto', border: '1px solid rgba(255,255,255,0.06)', borderRadius: '0.375rem' }}>
                                        {preview.details.filter(d => d.status === 'changed').map((row, i) => (
                                            <div key={i} style={{
                                                padding: '0.5rem 0.75rem',
                                                borderBottom: '1px solid rgba(255,255,255,0.04)',
                                                background: `${TEAL}05`,
                                            }}>
                                                <div style={{ fontFamily: 'monospace', fontSize: '0.75rem', color: '#E2E8F0', marginBottom: '0.25rem' }}>
                                                    {row.hostname}
                                                </div>
                                                {row.fields && Object.entries(row.fields).map(([field, vals]) => (
                                                    <div key={field} style={{ display: 'flex', gap: '0.5rem', fontSize: '0.68rem', fontFamily: 'monospace', marginLeft: '0.5rem' }}>
                                                        <span style={{ color: '#64748B', minWidth: '100px' }}>{field}:</span>
                                                        <span style={{ color: '#F87171', textDecoration: 'line-through' }}>{vals.old || '(empty)'}</span>
                                                        <span style={{ color: '#475569' }}>→</span>
                                                        <span style={{ color: EMERALD }}>{vals.new || '(empty)'}</span>
                                                    </div>
                                                ))}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Unmatched rows */}
                            {preview.unmatched_rows && preview.unmatched_rows.length > 0 && (
                                <div style={{ marginBottom: '1.25rem' }}>
                                    <div style={{ fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.08em', color: AMBER, marginBottom: '0.5rem' }}>
                                        Unmatched Hostnames ({preview.unmatched_rows.length})
                                    </div>
                                    <div style={{
                                        maxHeight: '100px', overflowY: 'auto',
                                        padding: '0.5rem 0.75rem',
                                        background: 'rgba(245,158,11,0.05)',
                                        border: '1px solid rgba(245,158,11,0.2)',
                                        borderRadius: '0.375rem',
                                        fontFamily: 'monospace', fontSize: '0.7rem', color: '#94A3B8',
                                    }}>
                                        {preview.unmatched_rows.join(', ')}
                                    </div>
                                </div>
                            )}

                            {/* Invalid rows */}
                            {preview.invalid_rows && preview.invalid_rows.length > 0 && (
                                <div style={{ marginBottom: '1.25rem' }}>
                                    <div style={{ fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.08em', color: RED, marginBottom: '0.5rem' }}>
                                        Invalid Rows ({preview.invalid_rows.length})
                                    </div>
                                    <div style={{
                                        maxHeight: '100px', overflowY: 'auto',
                                        padding: '0.5rem 0.75rem',
                                        background: 'rgba(239,68,68,0.05)',
                                        border: '1px solid rgba(239,68,68,0.2)',
                                        borderRadius: '0.375rem',
                                    }}>
                                        {preview.invalid_rows.map((row, i) => (
                                            <div key={i} style={{ fontFamily: 'monospace', fontSize: '0.7rem', color: '#F87171', marginBottom: '0.25rem' }}>
                                                {row.hostname}: {(row.errors || []).join('; ')}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Step: Done */}
                    {step === 'done' && commitResult && (
                        <div style={{ textAlign: 'center', padding: '2rem 0' }}>
                            <CheckCircle style={{ width: '40px', height: '40px', color: EMERALD, margin: '0 auto 1rem' }} />
                            <div style={{ fontFamily: 'monospace', fontSize: '0.9rem', color: '#E2E8F0', marginBottom: '0.5rem' }}>
                                Changes Committed
                            </div>
                            <div style={{ fontFamily: 'monospace', fontSize: '0.8rem', color: '#94A3B8' }}>
                                {commitResult.committed} device(s) updated
                            </div>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div style={{
                    display: 'flex', justifyContent: 'flex-end', gap: '0.75rem',
                    padding: '1rem 1.5rem',
                    borderTop: '1px solid rgba(255,255,255,0.06)',
                    flexShrink: 0,
                }}>
                    {step === 'preview' && !previewLoading && preview && (
                        <>
                            <button onClick={handleCancel} style={{
                                padding: '0.5rem 1.25rem',
                                background: 'transparent',
                                border: '1px solid rgba(100,116,139,0.4)',
                                borderRadius: '0.375rem',
                                color: '#94A3B8',
                                fontFamily: 'monospace', fontSize: '0.75rem',
                                cursor: 'pointer', transition: 'all 0.15s',
                            }}
                                onMouseEnter={e => e.currentTarget.style.borderColor = 'rgba(100,116,139,0.8)'}
                                onMouseLeave={e => e.currentTarget.style.borderColor = 'rgba(100,116,139,0.4)'}
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleCommit}
                                disabled={commitLoading || preview.changes === 0}
                                style={{
                                    padding: '0.5rem 1.25rem',
                                    background: preview.changes > 0 ? `${TEAL}18` : 'transparent',
                                    border: `1px solid ${preview.changes > 0 ? TEAL : 'rgba(100,116,139,0.3)'}`,
                                    borderRadius: '0.375rem',
                                    color: preview.changes > 0 ? TEAL : '#475569',
                                    fontFamily: 'monospace', fontSize: '0.75rem', fontWeight: '600',
                                    textTransform: 'uppercase', letterSpacing: '0.05em',
                                    cursor: preview.changes > 0 ? 'pointer' : 'default',
                                    opacity: commitLoading ? 0.6 : 1,
                                    display: 'flex', alignItems: 'center', gap: '0.4rem',
                                    transition: 'all 0.15s',
                                }}
                            >
                                {commitLoading && <Loader style={{ width: '14px', height: '14px', animation: 'spin 1s linear infinite' }} />}
                                Confirm ({preview.changes} changes)
                            </button>
                        </>
                    )}
                    {step === 'done' && (
                        <button onClick={onClose} style={{
                            padding: '0.5rem 1.25rem',
                            background: `${TEAL}18`,
                            border: `1px solid ${TEAL}`,
                            borderRadius: '0.375rem',
                            color: TEAL,
                            fontFamily: 'monospace', fontSize: '0.75rem', fontWeight: '600',
                            cursor: 'pointer', transition: 'all 0.15s',
                        }}>
                            Close
                        </button>
                    )}
                    {step === 'upload' && (
                        <button onClick={handleCancel} style={{
                            padding: '0.5rem 1.25rem',
                            background: 'transparent',
                            border: '1px solid rgba(100,116,139,0.4)',
                            borderRadius: '0.375rem',
                            color: '#94A3B8',
                            fontFamily: 'monospace', fontSize: '0.75rem',
                            cursor: 'pointer', transition: 'all 0.15s',
                        }}>
                            Cancel
                        </button>
                    )}
                </div>
            </div>
        </>
    );
}

function SummaryBadge({ label, value, color }) {
    return (
        <div style={{
            display: 'flex', alignItems: 'center', gap: '0.5rem',
            padding: '0.5rem 0.875rem',
            background: `${color}08`,
            border: `1px solid ${color}30`,
            borderRadius: '0.375rem',
        }}>
            <span style={{ fontFamily: 'monospace', fontSize: '1rem', fontWeight: '700', color }}>
                {value}
            </span>
            <span style={{ fontFamily: 'monospace', fontSize: '0.68rem', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                {label}
            </span>
        </div>
    );
}
