'use client';

import React, { useState, useEffect } from 'react';
import MainLayout from '@/components/layout/MainLayout';

type Farm = { id: string; name: string };
type Invoice = {
  id: string;
  farmId: string;
  farm: { name: string };
  invoiceNumber: string;
  amount: number;
  date: string;
};

export default function InvoicesPage() {
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [farms, setFarms] = useState<Farm[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);

  // Form state
  const [farmId, setFarmId] = useState('');
  const [invoiceNumber, setInvoiceNumber] = useState('');
  const [amount, setAmount] = useState('');
  const [date, setDate] = useState('');

  const fetchData = async () => {
    setLoading(true);
    try {
      const [invRes, farmRes] = await Promise.all([
        fetch('/api/farms/invoices'),
        fetch('/api/farms')
      ]);
      if (invRes.ok) setInvoices(await invRes.json());
      if (farmRes.ok) setFarms(await farmRes.json());
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/farms/invoices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ farmId, invoiceNumber, amount, date })
      });
      if (res.ok) {
        setIsModalOpen(false);
        fetchData();
        setFarmId(''); setInvoiceNumber(''); setAmount(''); setDate('');
      }
    } catch (e) {
      console.error(e);
    }
  };

  // Agrupar facturas por finca para el "Estado de Cuenta"
  const totalsByFarm = invoices.reduce((acc, inv) => {
    acc[inv.farm.name] = (acc[inv.farm.name] || 0) + inv.amount;
    return acc;
  }, {} as Record<string, number>);

  return (
    <MainLayout>
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
        <div>
          <h1 className="page-title" style={{ fontSize: '2.25rem', fontWeight: 800, color: 'var(--primary-color)' }}>Estado de Cuenta (Fincas)</h1>
          <p className="page-description" style={{ color: 'var(--text-secondary)' }}>Conciliación y registro de facturas por pagar a las fincas.</p>
        </div>
        <div style={{ display: 'flex', gap: '1rem' }}>
          <button className="btn-secondary" onClick={() => window.location.href = '/farms'}>
            ← Volver a Fincas
          </button>
          <button className="btn-primary" onClick={() => setIsModalOpen(true)}>
            + Registrar Factura
          </button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '2rem', alignItems: 'start' }}>
        {/* Tabla de Facturas */}
        <div className="glass-panel table-container">
          <h2 style={{ padding: '1.5rem', fontSize: '1.1rem', color: 'var(--primary-color)' }}>Historial de Facturas</h2>
          {loading ? (
            <div style={{ padding: '3rem', textAlign: 'center', color: 'var(--primary-color)' }}>Cargando...</div>
          ) : invoices.length === 0 ? (
            <div style={{ padding: '3rem', textAlign: 'center', color: 'var(--text-secondary)' }}>No hay facturas registradas.</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}>
              <thead>
                <tr style={{ background: 'rgba(28, 82, 54, 0.05)' }}>
                  <th style={{ padding: '1rem' }}>Fecha</th>
                  <th style={{ padding: '1rem' }}>Finca</th>
                  <th style={{ padding: '1rem' }}>N° Factura</th>
                  <th style={{ padding: '1rem', textAlign: 'right' }}>Monto (USD)</th>
                </tr>
              </thead>
              <tbody>
                {invoices.map((inv) => (
                  <tr key={inv.id} style={{ borderBottom: '1px solid var(--border-color)' }}>
                    <td style={{ padding: '1rem' }}>{new Date(inv.date).toLocaleDateString()}</td>
                    <td style={{ padding: '1rem', fontWeight: 600 }}>{inv.farm.name}</td>
                    <td style={{ padding: '1rem' }}>#{inv.invoiceNumber}</td>
                    <td style={{ padding: '1rem', textAlign: 'right', fontWeight: 600, color: '#065f46' }}>
                      ${inv.amount.toFixed(2)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* Resumen por Finca */}
        <div className="glass-panel" style={{ padding: '1.5rem' }}>
          <h2 style={{ fontSize: '1.1rem', color: 'var(--primary-color)', marginBottom: '1rem' }}>Total por Pagar</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
            {Object.entries(totalsByFarm).length === 0 ? (
              <div style={{ color: 'var(--text-secondary)', fontSize: '0.9rem' }}>No hay saldos.</div>
            ) : (
              Object.entries(totalsByFarm).map(([name, total]) => (
                <div key={name} style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '0.5rem', borderBottom: '1px solid var(--border-color)' }}>
                  <span style={{ fontWeight: 600, color: 'var(--text-secondary)' }}>{name}</span>
                  <span style={{ fontWeight: 700, color: '#92400e' }}>${total.toFixed(2)}</span>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {isModalOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(4px)' }}>
          <div className="auth-card" style={{ width: '100%', maxWidth: '400px', position: 'relative' }}>
            <button onClick={() => setIsModalOpen(false)} style={{ position: 'absolute', top: '1rem', right: '1rem', color: 'var(--text-secondary)' }}>✖</button>
            <h2 style={{ fontSize: '1.5rem', marginBottom: '1.5rem', color: 'var(--primary-color)' }}>Registrar Factura</h2>
            
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '0.25rem', color: 'var(--text-secondary)' }}>Finca</label>
                <select required value={farmId} onChange={e => setFarmId(e.target.value)} style={{ width: '100%', padding: '0.75rem', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-color)' }}>
                  <option value="">Selecciona una finca...</option>
                  {farms.map(f => (
                    <option key={f.id} value={f.id}>{f.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '0.25rem', color: 'var(--text-secondary)' }}>Número de Factura / Guía</label>
                <input required value={invoiceNumber} onChange={e => setInvoiceNumber(e.target.value)} placeholder="Ej: INV-00123" style={{ width: '100%', padding: '0.75rem', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-color)' }} />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '0.25rem', color: 'var(--text-secondary)' }}>Monto (USD)</label>
                <input required type="number" step="0.01" value={amount} onChange={e => setAmount(e.target.value)} placeholder="0.00" style={{ width: '100%', padding: '0.75rem', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-color)' }} />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '0.25rem', color: 'var(--text-secondary)' }}>Fecha</label>
                <input required type="date" value={date} onChange={e => setDate(e.target.value)} style={{ width: '100%', padding: '0.75rem', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-color)' }} />
              </div>

              <button type="submit" className="btn-primary" style={{ marginTop: '0.5rem' }}>Guardar Factura</button>
            </form>
          </div>
        </div>
      )}
    </MainLayout>
  );
}
