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 hoy = () => new Date().toISOString().split('T')[0];

const metodoLabels: Record<string, string> = {
  cash: 'Efectivo', card: 'Tarjeta', transfer: 'Transferencia',
  stripe: 'Stripe', mercadopago: 'MercadoPago',
};
const estadoLabels: Record<string, string> = {
  pending: 'Pendiente', processing: 'Procesando', completed: 'Completado',
  failed: 'Fallido', refunded: 'Reembolsado',
};

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 [fecha, setFecha] = useState(hoy());
  const [detalle, setDetalle] = useState<Payment | null>(null);

  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})` })),
  ];

  // Filtro por día (create_date "YYYY-MM-DD HH:MM"); vacío = todos
  const visibles = fecha
    ? payments.filter((p) => (p.create_date || '').startsWith(fecha))
    : payments;

  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>
          <div className="flex items-end gap-3 mb-4">
            <Input
              label="Fecha"
              type="date"
              value={fecha}
              onChange={(e) => setFecha(e.target.value)}
              className="sm:max-w-[180px]"
            />
            <Button
              variant={fecha === '' ? 'primary' : 'outline'}
              size="sm"
              onClick={() => setFecha(fecha === '' ? hoy() : '')}
              className="mb-1"
            >
              Todos
            </Button>
            <p className="text-sm text-theme-muted mb-1 sm:ml-auto">{visibles.length} cobros</p>
          </div>

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

          {loading ? (
            <Skeleton count={6} className="h-12 w-full" />
          ) : visibles.length === 0 ? (
            <EmptyState
              title="Sin pagos"
              subtitle={fecha ? 'No hay cobros registrados en esta fecha.' : '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-theme-bg">
                    <tr>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Referencia</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">Monto</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden sm:table-cell">Método</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Estado</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Acciones</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {visibles.map((p) => (
                      <tr key={p.id} className="hover:bg-theme-bg cursor-pointer" onClick={() => setDetalle(p)}>
                        <td className="p-3 text-sm text-theme-muted">{p.name}</td>
                        <td className="p-3 text-sm font-medium text-theme-heading">{p.patient}</td>
                        <td className="p-3 text-sm font-semibold text-theme-heading">${p.amount}</td>
                        <td className="p-3 text-sm text-theme-muted hidden sm:table-cell">{metodoLabels[p.payment_method] || p.payment_method}</td>
                        <td className="p-3">
                          <Badge variant={badgeForPaymentState(p.state)}>{estadoLabels[p.state] || p.state}</Badge>
                        </td>
                        <td className="p-3" onClick={(e) => e.stopPropagation()}>
                          {p.state !== 'confirmed' && p.state !== 'posted' && p.state !== 'completed' && (
                            <Button variant="ghost" size="sm" onClick={() => confirm(p.id)} title="Confirmar">
                              <CheckCircle size={16} className="text-theme-heading" />
                            </Button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

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

      {/* Modal detalle del cobro */}
      <Modal
        isOpen={!!detalle}
        onClose={() => setDetalle(null)}
        title={detalle ? `Cobro ${detalle.name}` : 'Detalle del cobro'}
        maxWidth="md"
      >
        {detalle && (
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Badge variant={badgeForPaymentState(detalle.state)}>{estadoLabels[detalle.state] || detalle.state}</Badge>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="p-3 bg-theme-bg rounded-xl">
                <p className="text-xs text-theme-muted mb-1">Paciente</p>
                <p className="text-sm font-medium text-theme-heading">{detalle.patient}</p>
              </div>
              <div className="p-3 bg-theme-bg rounded-xl">
                <p className="text-xs text-theme-muted mb-1">Monto</p>
                <p className="text-sm font-semibold text-theme-heading">${detalle.amount}</p>
              </div>
              <div className="p-3 bg-theme-bg rounded-xl">
                <p className="text-xs text-theme-muted mb-1">Método</p>
                <p className="text-sm font-medium text-theme-heading">{metodoLabels[detalle.payment_method] || detalle.payment_method}</p>
              </div>
              <div className="p-3 bg-theme-bg rounded-xl">
                <p className="text-xs text-theme-muted mb-1">Fecha de registro</p>
                <p className="text-sm font-medium text-theme-heading">{detalle.create_date || '-'}</p>
              </div>
              <div className="p-3 bg-theme-bg rounded-xl">
                <p className="text-xs text-theme-muted mb-1">Referencia proveedor</p>
                <p className="text-sm font-medium text-theme-heading break-words">{detalle.provider_reference || '-'}</p>
              </div>
            </div>
            {detalle.payment_url && (
              <a
                href={detalle.payment_url}
                target="_blank"
                rel="noreferrer"
                className="inline-flex items-center text-sm text-theme-heading underline"
              >
                Abrir link de pago
              </a>
            )}
          </div>
        )}
      </Modal>

      <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;
