import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Printer } from 'lucide-react';
import { Button, Modal, Select, TextArea } from './ui';
import { odooApi, type Receta } from '../services/odoo';

interface ClinicSettings {
  name: string;
  phone: string;
  address: string;
}

const clinicSettings = (): ClinicSettings => {
  try {
    const saved = localStorage.getItem('skeen_clinic_settings');
    if (saved) return JSON.parse(saved);
  } catch {
    // ignore
  }
  return { name: 'SKEEN Derma Experts', phone: '', address: '' };
};

interface RecetaSectionProps {
  value: string;
  onChange: (v: string) => void;
  onPrint: () => void;
}

/** Sección "Receta": plantilla + texto editable + imprimir (para modales de visita/consulta) */
export const RecetaSection: FC<RecetaSectionProps> = ({ value, onChange, onPrint }) => {
  const [recetas, setRecetas] = useState<Receta[]>([]);

  useEffect(() => {
    odooApi.getRecetas()
      .then((res) => { if (res.status === 'success') setRecetas(res.recetas); })
      .catch(() => {});
  }, []);

  const aplicarPlantilla = (id: string) => {
    if (!id) return;
    const r = recetas.find((x) => String(x.id) === id);
    if (r) onChange(r.contenido);
  };

  return (
    <section className="border-t border-theme-border pt-4">
      <div className="flex items-center justify-between mb-3">
        <h4 className="text-sm font-semibold text-theme-heading">Receta</h4>
        <Button variant="outline" size="sm" onClick={onPrint} disabled={!value.trim()}>
          <Printer size={14} className="mr-1.5" />
          Imprimir receta
        </Button>
      </div>
      <div className="space-y-3">
        <Select
          label="Usar plantilla"
          options={[
            { value: '', label: 'Selecciona plantilla...' },
            ...recetas.map((r) => ({ value: String(r.id), label: r.categoria ? `${r.name} (${r.categoria})` : r.name })),
          ]}
          value=""
          onChange={(e) => aplicarPlantilla(e.target.value)}
        />
        <TextArea
          label="Contenido de la receta"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Medicamentos, dosis e indicaciones..."
        />
      </div>
    </section>
  );
};

interface RecetaPrintProps {
  isOpen: boolean;
  onClose: () => void;
  paciente: string;
  doctor?: string | null;
  contenido: string;
}

/** Vista de impresión de la receta médica (formato imprimible) */
export const RecetaPrint: FC<RecetaPrintProps> = ({ isOpen, onClose, paciente, doctor, contenido }) => {
  const clinic = clinicSettings();
  const fecha = new Date().toLocaleDateString('es-MX', { day: '2-digit', month: 'long', year: 'numeric' });

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Vista de impresión — Receta médica"
      maxWidth="lg"
      footer={
        <>
          <Button variant="outline" onClick={onClose}>Cerrar</Button>
          <Button onClick={() => window.print()}>
            <Printer size={16} className="mr-2" />
            Imprimir
          </Button>
        </>
      }
    >
      <div className="print-receta bg-white text-[#222] p-6 rounded-xl border border-theme-border">
        {/* Encabezado clínica */}
        <div className="flex items-start justify-between border-b-2 border-[#1abc9c] pb-3 mb-4">
          <div>
            <p className="text-xl font-bold">{clinic.name}</p>
            {clinic.address && <p className="text-xs text-[#555]">{clinic.address}</p>}
            {clinic.phone && <p className="text-xs text-[#555]">Tel: {clinic.phone}</p>}
          </div>
          <p className="text-sm text-[#555]">{fecha}</p>
        </div>

        {/* Paciente */}
        <p className="text-sm mb-4">
          <span className="text-[#555]">Paciente: </span>
          <span className="font-semibold">{paciente}</span>
        </p>

        {/* Cuerpo */}
        <div className="flex gap-4 min-h-[220px]">
          <p className="text-4xl font-bold text-[#1abc9c] leading-none select-none">℞</p>
          <p className="text-sm whitespace-pre-wrap flex-1">{contenido}</p>
        </div>

        {/* Firma */}
        <div className="mt-10 text-center">
          <div className="inline-block border-t border-[#333] pt-1.5 px-8">
            <p className="text-sm font-semibold">{doctor || 'Médico tratante'}</p>
            <p className="text-xs text-[#555]">{clinic.name}</p>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default RecetaPrint;
