import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Plus, CheckCircle, CreditCard } from 'lucide-react';
import Layout from '../components/Layout';
import {
  Card,
  Button,
  Input,
  Select,
  Modal,
  Badge,
  EmptyState,
  PageHeader,
  Skeleton,
  MobileCard,
  toast,
  badgeForPaymentState,
} from '../components/ui';
import { odooApi, type Payment, type Patient } from '../services/odoo';

const methods = ['Efectivo', 'Tarjeta', 'Transferencia', 'MercadoPago', 'Stripe'];

const methodOptions = methods.map((m) => ({ value: m, label: m }));

const Pagos: FC = () => {
  const [payments, setPayments] = useState<Payment[]>([]);
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [patient, setPatient] = useState('');
  const [amount, setAmount] = useState('');
  const [method, setMethod] = useState('Efectivo');

  const load = async () => {
    try {
      setLoading(true);
      setError(null);
      const [paymentsRes, patientsRes] = await Promise.all([
        odooApi.getPayments(),
        odooApi.getPatients(),
      ]);
      if (paymentsRes.status === 'success') setPayments(paymentsRes.payments);
      if (patientsRes.status === 'success') setPatients(patientsRes.patients);
    } catch (err) {
      setError('Error al cargar pagos');
      toast.error('Error al cargar pagos');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const create = async () => {
    const value = parseFloat(amount);
    if (!patient || Number.isNaN(value) || value <= 0) {
      toast.error('Selecciona paciente e ingresa un monto válido');
      return;
    }
    try {
      setSubmitting(true);
      await odooApi.createPayment({ patient, amount: value, payment_method: method });
      toast.success('Pago creado');
      setModalOpen(false);
      setPatient('');
      setAmount('');
      setMethod('Efectivo');
      await load();
    } catch (err) {
      toast.error('Error al crear pago');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const confirm = async (id: number) => {
    try {
      await odooApi.confirmPayment(id);
      toast.success('Pago confirmado');
      await load();
    } catch (err) {
      toast.error('Error al confirmar pago');
      console.error(err);
    }
  };

  const patientOptions = [
    { value: '', label: 'Seleccionar paciente...' },
    ...patients.map((p) => ({ value: p.name, label: `${p.name} (${p.phone})` })),
  ];

  return (
    <Layout title="Pagos" subtitle="Transacciones">
      <PageHeader title="Pagos" subtitle="Crea y confirma pagos">
        <Button onClick={() => setModalOpen(true)}>
          <Plus size={16} className="mr-2" />
          Nuevo pago
        </Button>
      </PageHeader>

      <Card>
        <Card.Body>
          {error && <p className="text-rose-600 text-sm mb-4">{error}</p>}

          {loading ? (
            <Skeleton count={6} className="h-12 w-full" />
          ) : payments.length === 0 ? (
            <EmptyState
              title="Sin pagos"
              subtitle="No hay pagos registrados."
              actionLabel="Nuevo pago"
              onAction={() => setModalOpen(true)}
              icon={<CreditCard size={28} />}
            />
          ) : (
            <>
              <div className="hidden sm:block overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-[#FEF3C7]">
                    <tr>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Referencia</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Paciente</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Monto</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase hidden sm:table-cell">Método</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Estado</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Acciones</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {payments.map((p) => (
                      <tr key={p.id} className="hover:bg-[#FEF3C7]">
                        <td className="p-3 text-sm text-[#7A5C44]">{p.name}</td>
                        <td className="p-3 text-sm font-medium text-homenest-bark">{p.patient}</td>
                        <td className="p-3 text-sm font-semibold text-homenest-bark">${p.amount}</td>
                        <td className="p-3 text-sm text-[#7A5C44] hidden sm:table-cell">{p.payment_method}</td>
                        <td className="p-3">
                          <Badge variant={badgeForPaymentState(p.state)}>{p.state}</Badge>
                        </td>
                        <td className="p-3">
                          {p.state !== 'confirmed' && p.state !== 'posted' && (
                            <Button variant="ghost" size="sm" onClick={() => confirm(p.id)} title="Confirmar">
                              <CheckCircle size={16} className="text-#3E2C1C" />
                            </Button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="sm:hidden space-y-3">
                {payments.map((p) => (
                  <MobileCard
                    key={p.id}
                    title={p.patient}
                    subtitle={p.name}
                    rows={[
                      { label: 'Monto', value: `$${p.amount}` },
                      { label: 'Método', value: p.payment_method },
                      { label: 'Estado', value: <Badge variant={badgeForPaymentState(p.state)}>{p.state}</Badge> },
                    ]}
                    actions={
                      p.state !== 'confirmed' && p.state !== 'posted' && (
                        <Button variant="ghost" size="sm" onClick={() => confirm(p.id)}>
                          <CheckCircle size={16} className="text-#3E2C1C" />
                        </Button>
                      )
                    }
                  />
                ))}
              </div>
            </>
          )}
        </Card.Body>
      </Card>

      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title="Nuevo pago"
        maxWidth="sm"
        footer={
          <>
            <Button variant="outline" onClick={() => setModalOpen(false)}>Cancelar</Button>
            <Button onClick={create} loading={submitting}>Crear pago</Button>
          </>
        }
      >
        <div className="space-y-4">
          <Select
            label="Paciente *"
            options={patientOptions}
            value={patient}
            onChange={(e) => setPatient(e.target.value)}
          />
          <Input
            label="Monto *"
            type="number"
            min={0.01}
            step={0.01}
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
          />
          <Select
            label="Método de pago"
            options={methodOptions}
            value={method}
            onChange={(e) => setMethod(e.target.value)}
          />
        </div>
      </Modal>
    </Layout>
  );
};

export default Pagos;
