import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Plus, Search, ClipboardPlus } from 'lucide-react';
import Layout from '../components/Layout';
import { RecetaSection, RecetaPrint } from '../components/RecetaPrint';
import {
  Card,
  Button,
  Input,
  Select,
  TextArea,
  Modal,
  Badge,
  EmptyState,
  PageHeader,
  Skeleton,
  toast,
} from '../components/ui';
import { odooApi, type Visita, type Doctor, type Patient, type Diagnostico } from '../services/odoo';

const hoy = () => new Date().toISOString().split('T')[0];

const Consultas: FC = () => {
  const [consultas, setConsultas] = useState<Visita[]>([]);
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [diagnosticos, setDiagnosticos] = useState<Diagnostico[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [fecha, setFecha] = useState(hoy());
  const [doctorFiltro, setDoctorFiltro] = useState('');
  const [busqueda, setBusqueda] = useState('');

  // Modal nueva consulta
  const [modalNueva, setModalNueva] = useState(false);
  const [pacienteQuery, setPacienteQuery] = useState('');
  const [pacienteResults, setPacienteResults] = useState<Patient[]>([]);
  const [pacienteSel, setPacienteSel] = useState<Patient | null>(null);
  const [formNueva, setFormNueva] = useState({
    doctor_id: '',
    motivo: '',
    diag_sel: '',
    diag_libre: '',
    tratamiento: '',
    notas: '',
  });

  // Modal edición
  const [selected, setSelected] = useState<Visita | null>(null);
  const [formEdit, setFormEdit] = useState({ motivo: '', diagnostico: '', tratamiento: '', notas: '', receta_text: '', doctor_id: '' });
  const [printOpen, setPrintOpen] = useState(false);

  const doctorOptions = [
    { value: '', label: 'Sin asignar' },
    ...doctors.map((d) => ({ value: String(d.id), label: d.name })),
  ];

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const params: Record<string, string | number> = { origen: 'consulta', page_size: 100 };
      params.date = fecha || 'todas';
      if (doctorFiltro) params.doctor_id = doctorFiltro;
      if (busqueda) params.search = busqueda;
      const res = await odooApi.getVisitas(params);
      if (res.status === 'success') setConsultas(res.visitas);
    } catch (err) {
      toast.error('Error al cargar consultas');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [fecha, doctorFiltro, busqueda]);

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

  useEffect(() => {
    odooApi.getDoctors()
      .then((res) => { if (res.status === 'success') setDoctors(res.doctors); })
      .catch(() => {});
    odooApi.getDiagnosticos()
      .then((res) => { if (res.status === 'success') setDiagnosticos(res.items); })
      .catch(() => {});
  }, []);

  // Búsqueda server-side de paciente para el modal
  useEffect(() => {
    if (!modalNueva || pacienteSel) return;
    if (pacienteQuery.trim().length < 2) {
      setPacienteResults([]);
      return;
    }
    const t = setTimeout(() => {
      odooApi.getPatients({ search: pacienteQuery.trim(), page_size: 8 })
        .then((res) => { if (res.status === 'success') setPacienteResults(res.patients); })
        .catch(() => {});
    }, 300);
    return () => clearTimeout(t);
  }, [pacienteQuery, modalNueva, pacienteSel]);

  const openNueva = () => {
    setPacienteSel(null);
    setPacienteQuery('');
    setPacienteResults([]);
    setFormNueva({ doctor_id: '', motivo: '', diag_sel: '', diag_libre: '', tratamiento: '', notas: '' });
    setModalNueva(true);
  };

  const guardarNueva = async () => {
    if (!pacienteSel) {
      toast.error('Selecciona un paciente');
      return;
    }
    const diagnostico = formNueva.diag_sel
      ? (diagnosticos.find((d) => String(d.id) === formNueva.diag_sel)?.name || '')
      : formNueva.diag_libre.trim();
    try {
      setSubmitting(true);
      const res = await odooApi.createConsulta({
        partner_id: pacienteSel.id,
        doctor_id: formNueva.doctor_id ? parseInt(formNueva.doctor_id, 10) : null,
        motivo: formNueva.motivo,
        diagnostico,
        tratamiento: formNueva.tratamiento,
        notas: formNueva.notas,
      });
      if (res.status === 'success') {
        toast.success('Consulta registrada');
        setModalNueva(false);
        await load();
      }
    } catch (err) {
      toast.error('Error al registrar la consulta');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const openEdit = (v: Visita) => {
    setSelected(v);
    setFormEdit({
      motivo: v.motivo || '',
      diagnostico: v.diagnostico || '',
      tratamiento: v.tratamiento || '',
      notas: v.notas || '',
      receta_text: v.receta_text || '',
      doctor_id: v.doctor_id ? String(v.doctor_id) : '',
    });
  };

  const guardarEdicion = async () => {
    if (!selected) return;
    try {
      setSubmitting(true);
      const res = await odooApi.updateVisita(selected.id, {
        motivo: formEdit.motivo,
        diagnostico: formEdit.diagnostico,
        tratamiento: formEdit.tratamiento,
        notas: formEdit.notas,
        receta_text: formEdit.receta_text,
        doctor_id: formEdit.doctor_id ? parseInt(formEdit.doctor_id, 10) : null,
      });
      if (res.status === 'success') {
        toast.success('Consulta actualizada');
        setSelected(null);
        await load();
      }
    } catch (err) {
      toast.error('Error al actualizar la consulta');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Layout title="Consultas Médicas" subtitle="Registro directo de consultas">
      <PageHeader title="Consultas Médicas" subtitle="Consultas registradas sin cita previa">
        <Button onClick={openNueva}>
          <Plus size={16} className="mr-2" />
          Nueva consulta
        </Button>
      </PageHeader>

      <Card>
        <Card.Body>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4 sm:mb-6">
            <div className="flex items-end gap-2">
              <div className="flex-1">
                <Input label="Fecha" type="date" value={fecha === 'todas' ? '' : fecha} onChange={(e) => setFecha(e.target.value || 'todas')} />
              </div>
              <Button
                variant={fecha === 'todas' ? 'primary' : 'outline'}
                size="sm"
                onClick={() => setFecha(fecha === 'todas' ? hoy() : 'todas')}
                className="mb-1"
              >
                Todas
              </Button>
            </div>
            <Select
              label="Médico"
              options={[{ value: '', label: 'Todos' }, ...doctorOptions.slice(1)]}
              value={doctorFiltro}
              onChange={(e) => setDoctorFiltro(e.target.value)}
            />
            <Input label="Paciente" placeholder="Buscar por nombre..." value={busqueda} onChange={(e) => setBusqueda(e.target.value)} />
          </div>

          {loading ? (
            <Skeleton count={6} className="h-12 w-full" />
          ) : consultas.length === 0 ? (
            <EmptyState
              title="Sin consultas"
              subtitle="No hay consultas registradas con los filtros seleccionados."
              actionLabel="Nueva consulta"
              onAction={openNueva}
              icon={<ClipboardPlus size={28} />}
            />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-theme-bg">
                  <tr>
                    <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Fecha</th>
                    <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Paciente</th>
                    <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Motivo</th>
                    <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Diagnóstico</th>
                    <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden sm:table-cell">Médico</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {consultas.map((c) => (
                    <tr key={c.id} className="hover:bg-theme-bg cursor-pointer" onClick={() => openEdit(c)}>
                      <td className="p-3 text-sm text-theme-muted whitespace-nowrap">{c.date_start || '-'}</td>
                      <td className="p-3 text-sm font-medium text-theme-heading">{c.patient}</td>
                      <td className="p-3 text-sm text-theme-muted">{c.motivo || '-'}</td>
                      <td className="p-3 text-sm text-theme-muted hidden md:table-cell">
                        <span className="block max-w-[220px] truncate">{c.diagnostico || '-'}</span>
                      </td>
                      <td className="p-3 text-sm text-theme-muted hidden sm:table-cell">{c.doctor || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card.Body>
      </Card>

      {/* Modal nueva consulta */}
      <Modal
        isOpen={modalNueva}
        onClose={() => setModalNueva(false)}
        title="Nueva consulta"
        maxWidth="2xl"
        footer={
          <>
            <Button variant="outline" onClick={() => setModalNueva(false)}>Cancelar</Button>
            <Button onClick={guardarNueva} loading={submitting} disabled={!pacienteSel}>Guardar consulta</Button>
          </>
        }
      >
        <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-1">
          {/* Paciente */}
          <div>
            <p className="text-sm font-medium text-theme-heading mb-1.5">Paciente *</p>
            {pacienteSel ? (
              <div className="flex items-center justify-between p-3 bg-theme-bg rounded-xl">
                <span className="text-sm font-medium text-theme-heading">{pacienteSel.name} <span className="text-theme-muted">· {pacienteSel.phone}</span></span>
                <Button variant="ghost" size="sm" onClick={() => { setPacienteSel(null); setPacienteQuery(''); }}>
                  Cambiar
                </Button>
              </div>
            ) : (
              <div className="relative">
                <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-theme-muted" />
                <Input
                  placeholder="Buscar por nombre o teléfono..."
                  value={pacienteQuery}
                  onChange={(e) => setPacienteQuery(e.target.value)}
                  className="pl-10"
                />
                {pacienteResults.length > 0 && (
                  <div className="absolute z-20 top-full left-0 right-0 mt-1 rounded-xl border border-theme-border bg-theme-surface shadow-card max-h-56 overflow-y-auto">
                    {pacienteResults.map((p) => (
                      <button
                        key={p.id}
                        type="button"
                        onClick={() => { setPacienteSel(p); setPacienteResults([]); }}
                        className="w-full text-left px-3 py-2.5 text-sm hover:bg-theme-bg transition"
                      >
                        <span className="font-medium text-theme-heading">{p.name}</span>
                        <span className="text-theme-muted"> · {p.phone}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          <Select
            label="Médico / Atendió"
            options={doctorOptions}
            value={formNueva.doctor_id}
            onChange={(e) => setFormNueva({ ...formNueva, doctor_id: e.target.value })}
          />
          <Input
            label="Motivo de consulta"
            value={formNueva.motivo}
            onChange={(e) => setFormNueva({ ...formNueva, motivo: e.target.value })}
          />
          <Select
            label="Diagnóstico (catálogo)"
            options={[
              { value: '', label: 'Texto libre / sin diagnóstico' },
              ...diagnosticos.map((d) => ({ value: String(d.id), label: d.name })),
            ]}
            value={formNueva.diag_sel}
            onChange={(e) => setFormNueva({ ...formNueva, diag_sel: e.target.value })}
          />
          {!formNueva.diag_sel && (
            <TextArea
              label="Diagnóstico (texto libre)"
              value={formNueva.diag_libre}
              onChange={(e) => setFormNueva({ ...formNueva, diag_libre: e.target.value })}
            />
          )}
          <TextArea
            label="Tratamiento"
            value={formNueva.tratamiento}
            onChange={(e) => setFormNueva({ ...formNueva, tratamiento: e.target.value })}
          />
          <TextArea
            label="Observaciones"
            value={formNueva.notas}
            onChange={(e) => setFormNueva({ ...formNueva, notas: e.target.value })}
          />
        </div>
      </Modal>

      {/* Modal edición */}
      <Modal
        isOpen={!!selected}
        onClose={() => setSelected(null)}
        title={selected ? `Consulta — ${selected.patient}` : 'Consulta'}
        maxWidth="2xl"
        footer={
          <>
            <Button variant="outline" onClick={() => setSelected(null)}>Cerrar</Button>
            <Button onClick={guardarEdicion} loading={submitting}>Guardar</Button>
          </>
        }
      >
        {selected && (
          <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-1">
            <div className="flex flex-wrap items-center gap-2">
              <Badge variant="success">Completada</Badge>
              <span className="text-sm text-theme-muted">{selected.date_start || '-'}</span>
            </div>
            <Select
              label="Médico / Atendió"
              options={doctorOptions}
              value={formEdit.doctor_id}
              onChange={(e) => setFormEdit({ ...formEdit, doctor_id: e.target.value })}
            />
            <Input label="Motivo" value={formEdit.motivo} onChange={(e) => setFormEdit({ ...formEdit, motivo: e.target.value })} />
            <TextArea label="Diagnóstico" value={formEdit.diagnostico} onChange={(e) => setFormEdit({ ...formEdit, diagnostico: e.target.value })} />
            <TextArea label="Tratamiento" value={formEdit.tratamiento} onChange={(e) => setFormEdit({ ...formEdit, tratamiento: e.target.value })} />
            <TextArea label="Observaciones" value={formEdit.notas} onChange={(e) => setFormEdit({ ...formEdit, notas: e.target.value })} />
            <RecetaSection
              value={formEdit.receta_text}
              onChange={(v) => setFormEdit({ ...formEdit, receta_text: v })}
              onPrint={() => setPrintOpen(true)}
            />
          </div>
        )}
      </Modal>

      {/* Vista de impresión de la receta */}
      {selected && (
        <RecetaPrint
          isOpen={printOpen}
          onClose={() => setPrintOpen(false)}
          paciente={selected.patient}
          doctor={selected.doctor}
          contenido={formEdit.receta_text}
        />
      )}
    </Layout>
  );
};

export default Consultas;
