import type { FC } from 'react';
import { useEffect, useState, useCallback, useRef } from 'react';
import { FileText, X, Upload } from 'lucide-react';
import { Button, Modal, Skeleton, toast } from './ui';
import { odooApi, type PatientAdjunto } from '../services/odoo';

interface PatientAdjuntosProps {
  patientId: number;
  kind: 'expediente' | 'imagen';
  editable?: boolean;
  onChange?: () => void;
}

const MAX_BYTES = 10 * 1024 * 1024;

export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, editable = true, onChange }) => {
  const [adjuntos, setAdjuntos] = useState<PatientAdjunto[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [visor, setVisor] = useState<PatientAdjunto | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getPatientAdjuntos(patientId, kind);
      if (res.status === 'success') setAdjuntos(res.adjuntos);
    } catch (err) {
      toast.error('Error al cargar archivos');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [patientId, kind]);

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

  const subir = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    e.target.value = '';
    if (!file) return;
    if (file.size > MAX_BYTES) {
      toast.error('El archivo excede 10 MB');
      return;
    }
    const reader = new FileReader();
    reader.onload = async () => {
      const file_b64 = String(reader.result || '').split(',')[1] || '';
      try {
        setUploading(true);
        const res = await odooApi.uploadPatientAdjunto(patientId, {
          kind,
          name: file.name,
          file_b64,
          mimetype: file.type || 'application/octet-stream',
        });
        if (res.status === 'success') {
          toast.success('Archivo subido');
          await load();
          onChange?.();
        }
      } catch (err) {
        toast.error('Error al subir el archivo');
        console.error(err);
      } finally {
        setUploading(false);
      }
    };
    reader.readAsDataURL(file);
  };

  const borrar = async (adjId: number) => {
    if (!window.confirm('¿Eliminar este archivo?')) return;
    try {
      await odooApi.deletePatientAdjunto(adjId);
      toast.success('Archivo eliminado');
      await load();
      onChange?.();
    } catch (err) {
      toast.error('Error al eliminar el archivo');
      console.error(err);
    }
  };

  const imagenes = adjuntos.filter((a) => a.mimetype.startsWith('image/'));
  const docs = adjuntos.filter((a) => !a.mimetype.startsWith('image/'));

  return (
    <div>
      {editable && (
        <div className="mb-3">
          <input
            ref={fileRef}
            type="file"
            accept={kind === 'imagen' ? 'image/*' : undefined}
            className="hidden"
            onChange={subir}
          />
          <Button variant="outline" size="sm" onClick={() => fileRef.current?.click()} loading={uploading}>
            <Upload size={14} className="mr-1.5" />
            {kind === 'imagen' ? 'Subir foto' : 'Escanear / Subir expediente'}
          </Button>
        </div>
      )}

      {loading ? (
        <Skeleton count={2} className="h-16 w-full" />
      ) : adjuntos.length === 0 ? (
        <p className="text-sm text-theme-muted">
          {kind === 'imagen' ? 'Sin fotos en la galería.' : 'Sin expediente escaneado.'}
        </p>
      ) : (
        <>
          {imagenes.length > 0 && (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-3">
              {imagenes.map((a) => (
                <div key={a.id} className="relative">
                  <button type="button" onClick={() => setVisor(a)} className="w-full">
                    <img
                      src={odooApi.patientAdjuntoUrl(a.url)}
                      alt={a.name}
                      className="w-full h-24 object-cover rounded-xl border border-theme-border"
                    />
                  </button>
                  {editable && (
                    <button
                      type="button"
                      onClick={() => borrar(a.id)}
                      title="Eliminar"
                      className="absolute top-1 right-1 p-1 rounded-full bg-theme-surface/90 text-theme-muted hover:text-rose-600"
                    >
                      <X size={12} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}
          {docs.length > 0 && (
            <ul className="space-y-1">
              {docs.map((a) => (
                <li key={a.id} className="flex items-center justify-between p-2 bg-theme-bg rounded-lg text-sm">
                  <a
                    href={odooApi.patientAdjuntoUrl(a.url)}
                    target="_blank"
                    rel="noreferrer"
                    className="flex items-center text-theme-heading hover:underline min-w-0"
                  >
                    <FileText size={14} className="mr-1.5 text-theme-muted shrink-0" />
                    <span className="truncate">{a.name}</span>
                  </a>
                  {editable && (
                    <Button variant="ghost" size="sm" onClick={() => borrar(a.id)} title="Eliminar">
                      <X size={14} className="text-theme-muted" />
                    </Button>
                  )}
                </li>
              ))}
            </ul>
          )}
        </>
      )}

      {/* Visor de imagen */}
      <Modal
        isOpen={!!visor}
        onClose={() => setVisor(null)}
        title={visor?.name || 'Imagen'}
        maxWidth="2xl"
      >
        {visor && (
          <img
            src={odooApi.patientAdjuntoUrl(visor.url)}
            alt={visor.name}
            className="w-full rounded-xl"
          />
        )}
      </Modal>
    </div>
  );
};

export default PatientAdjuntos;
