import React, { useState } from 'react';
import { User, Lock, Eye, EyeOff, FileText, Download, Printer, LogOut, ArrowLeft } from 'lucide-react';

interface PacienteData {
    id: number;
    ci: string;
    nombre: string;
    apellido: string;
    celular: string;
    sexo: string;
    examen: {
        id: number;
        nombre: string;
    };
    resultados: Array<{
        id: number;
        archivo_nombre: string;
        archivo_tipo: string;
        archivo_tamano: number;
        observaciones: string | null;
        subido_en: string;
    }>;
}

export default function PatientPortal() {
    const [ci, setCi] = useState('');
    const [celular, setCelular] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [paciente, setPaciente] = useState<PacienteData | null>(null);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError('');

        try {
            const response = await fetch('/api/pacientes/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ ci, celular }),
            });

            const data = await response.json();

            if (data.success) {
                setPaciente(data.data);
            } else {
                setError(data.message || 'Error al iniciar sesión');
            }
        } catch (err) {
            setError('Error de conexión. Por favor intente más tarde.');
        } finally {
            setLoading(false);
        }
    };

    const handleLogout = () => {
        setPaciente(null);
        setCi('');
        setCelular('');
        setError('');
    };

    const handleDownload = (resultadoId: number) => {
        window.open(`/api/resultados/${resultadoId}/download`, '_blank');
    };

    const handleView = (resultadoId: number) => {
        window.open(`/api/resultados/${resultadoId}/view`, '_blank');
    };

    const handlePrint = () => {
        window.print();
    };

    const formatFileSize = (bytes: number) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // Login View
    if (!paciente) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-blue-50 to-cyan-50 flex items-center justify-center p-4">
                <div className="w-full max-w-md">
                    {/* Logo / Header */}
                    <div className="text-center mb-8">
                        <div className="w-20 h-20 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-2xl mx-auto flex items-center justify-center shadow-lg mb-4">
                            <FileText className="w-10 h-10 text-white" />
                        </div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2">
                            Portal del Paciente
                        </h1>
                        <p className="text-gray-600">
                            Cibertronia Salud
                        </p>
                    </div>

                    {/* Login Form */}
                    <div className="bg-white rounded-2xl shadow-xl p-8">
                        <h2 className="text-xl font-semibold text-gray-900 mb-6 text-center">
                            Acceder a mis exámenes
                        </h2>

                        {error && (
                            <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-200 text-red-700 text-sm">
                                {error}
                            </div>
                        )}

                        <form onSubmit={handleLogin} className="space-y-5">
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-2">
                                    Cédula de Identidad (C.I.)
                                </label>
                                <div className="relative">
                                    <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                                    <input
                                        type="text"
                                        value={ci}
                                        onChange={(e) => setCi(e.target.value)}
                                        placeholder="Ej: 1234567"
                                        className="w-full pl-10 pr-4 py-3 rounded-xl border-2 border-gray-200 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all outline-none"
                                        required
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-2">
                                    Número de Celular
                                </label>
                                <div className="relative">
                                    <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                                    <input
                                        type={showPassword ? 'text' : 'password'}
                                        value={celular}
                                        onChange={(e) => setCelular(e.target.value)}
                                        placeholder="Ej: 77712345"
                                        className="w-full pl-10 pr-12 py-3 rounded-xl border-2 border-gray-200 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all outline-none"
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                    >
                                        {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                                    </button>
                                </div>
                            </div>

                            <button
                                type="submit"
                                disabled={loading}
                                className="w-full py-3 bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded-xl font-semibold shadow-lg hover:shadow-xl transform hover:scale-[1.02] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                {loading ? (
                                    <>
                                        <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                                        Verificando...
                                    </>
                                ) : (
                                    'Ingresar'
                                )}
                            </button>
                        </form>

                        <div className="mt-6 text-center">
                            <p className="text-sm text-gray-500">
                                Ingrese su C.I. y número de celular registrado
                            </p>
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="mt-8 text-center">
                        <p className="text-sm text-gray-500">
                            © 2024 Cibertronia Salud. Todos los derechos reservados.
                        </p>
                        <a 
                            href="/" 
                            className="inline-flex items-center gap-2 mt-2 text-blue-600 hover:text-blue-700 text-sm font-medium"
                        >
                            <ArrowLeft className="w-4 h-4" />
                            Volver al inicio
                        </a>
                    </div>
                </div>
            </div>
        );
    }

    // Dashboard View
    return (
        <div className="min-h-screen bg-gradient-to-br from-blue-50 to-cyan-50">
            {/* Header */}
            <header className="bg-white shadow-sm border-b border-gray-200">
                <div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-xl flex items-center justify-center">
                            <FileText className="w-6 h-6 text-white" />
                        </div>
                        <div>
                            <h1 className="text-xl font-bold text-gray-900">Portal del Paciente</h1>
                            <p className="text-sm text-gray-500">Cibertronia Salud</p>
                        </div>
                    </div>
                    <button
                        onClick={handleLogout}
                        className="flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 rounded-xl transition-colors"
                    >
                        <LogOut className="w-5 h-5" />
                        <span className="hidden sm:inline">Cerrar Sesión</span>
                    </button>
                </div>
            </header>

            {/* Main Content */}
            <main className="max-w-6xl mx-auto px-4 py-8">
                {/* Patient Info Card */}
                <div className="bg-white rounded-2xl shadow-lg p-6 mb-6">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div>
                            <h2 className="text-2xl font-bold text-gray-900">
                                {paciente.apellido}, {paciente.nombre}
                            </h2>
                            <div className="flex flex-wrap gap-4 mt-2 text-sm text-gray-600">
                                <span className="flex items-center gap-1">
                                    <User className="w-4 h-4" />
                                    C.I.: {paciente.ci}
                                </span>
                                <span className="flex items-center gap-1">
                                    <FileText className="w-4 h-4" />
                                    {paciente.sexo}
                                </span>
                            </div>
                        </div>
                        <div className="text-left md:text-right">
                            <p className="text-sm text-gray-500">Examen solicitado</p>
                            <p className="text-lg font-semibold text-blue-600">{paciente.examen.nombre}</p>
                        </div>
                    </div>
                </div>

                {/* Results Section */}
                <div className="bg-white rounded-2xl shadow-lg overflow-hidden">
                    <div className="p-6 border-b border-gray-200 flex items-center justify-between">
                        <h3 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                            <FileText className="w-6 h-6 text-blue-500" />
                            Mis Resultados
                        </h3>
                        {paciente.resultados.length > 0 && (
                            <button
                                onClick={handlePrint}
                                className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl transition-colors"
                            >
                                <Printer className="w-4 h-4" />
                                Imprimir
                            </button>
                        )}
                    </div>

                    <div className="p-6">
                        {paciente.resultados.length === 0 ? (
                            <div className="text-center py-12">
                                <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <FileText className="w-10 h-10 text-gray-400" />
                                </div>
                                <h4 className="text-lg font-semibold text-gray-900 mb-2">
                                    No hay resultados disponibles
                                </h4>
                                <p className="text-gray-600 max-w-md mx-auto">
                                    Sus resultados aún no han sido subidos al sistema. 
                                    Por favor, contacte a la clínica para más información.
                                </p>
                            </div>
                        ) : (
                            <div className="space-y-4">
                                {paciente.resultados.map((resultado) => (
                                    <div
                                        key={resultado.id}
                                        className="border border-gray-200 rounded-xl p-4 hover:shadow-md transition-shadow"
                                    >
                                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                            <div className="flex-1">
                                                <div className="flex items-center gap-3 mb-2">
                                                    <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                                                        <FileText className="w-5 h-5 text-blue-600" />
                                                    </div>
                                                    <div>
                                                        <h4 className="font-semibold text-gray-900">
                                                            {resultado.archivo_nombre}
                                                        </h4>
                                                        <p className="text-sm text-gray-500">
                                                            {formatFileSize(resultado.archivo_tamano)} • Subido el {new Date(resultado.subido_en).toLocaleDateString('es-BO')}
                                                        </p>
                                                    </div>
                                                </div>
                                                {resultado.observaciones && (
                                                    <p className="text-sm text-gray-600 mt-2 pl-13 ml-12">
                                                        <span className="font-medium">Observaciones:</span> {resultado.observaciones}
                                                    </p>
                                                )}
                                            </div>
                                            <div className="flex gap-2">
                                                <button
                                                    onClick={() => handleView(resultado.id)}
                                                    className="flex items-center gap-2 px-4 py-2 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-xl transition-colors"
                                                >
                                                    <Eye className="w-4 h-4" />
                                                    Ver
                                                </button>
                                                <button
                                                    onClick={() => handleDownload(resultado.id)}
                                                    className="flex items-center gap-2 px-4 py-2 bg-green-100 hover:bg-green-200 text-green-700 rounded-xl transition-colors"
                                                >
                                                    <Download className="w-4 h-4" />
                                                    Descargar
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* Help Section */}
                <div className="mt-8 bg-blue-50 rounded-2xl p-6 border border-blue-100">
                    <h4 className="font-semibold text-blue-900 mb-2">¿Necesita ayuda?</h4>
                    <p className="text-blue-700 text-sm mb-4">
                        Si tiene problemas para acceder a sus resultados o necesita asistencia, 
                        por favor contacte a nuestra recepción.
                    </p>
                    <div className="flex flex-wrap gap-4 text-sm text-blue-600">
                        <span>Teléfono: (2) 123-4567</span>
                        <span>Email: info@cibertroniasalud.com</span>
                    </div>
                </div>
            </main>

            {/* Print Styles */}
            <style>{`
                @media print {
                    header, .no-print { display: none !important; }
                    .shadow-lg { box-shadow: none !important; }
                    body { background: white !important; }
                }
            `}</style>
        </div>
    );
}
