'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';

const API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';

const BILLING_LABELS: Record<string, string> = {
  monthly: 'Mensal', yearly: 'Anual', once: 'Único', hourly: 'Por hora',
};

type ProposalItem = {
  name: string; description?: string; billingCycle?: string;
  unitPrice: number; quantity: number; discount: number; total: number;
};

type ProposalData = {
  id: string; number: string; title?: string; status: string;
  validUntil?: string; notes?: string; billingCycle?: string; paymentTerms?: string;
  subtotal: number; discount: number; total: number; createdAt: string;
  tenantName: string; logoUrl?: string;
  clientName: string; clientDocument?: string;
  items: ProposalItem[];
};

type Phase = 'loading' | 'ready' | 'accepting' | 'accepted' | 'rejected' | 'error';

const fmt = (v: number) => v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
const fmtDate = (d: string) => new Date(d + 'T00:00:00').toLocaleDateString('pt-BR');

export default function PublicProposalPage() {
  const params = useParams();
  const tenantId = params.tenantId as string;
  const id = params.id as string;

  const [phase, setPhase] = useState<Phase>('loading');
  const [proposal, setProposal] = useState<ProposalData | null>(null);
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    if (!tenantId || !id) return;

    // Register view
    fetch(`${API}/proposals/${tenantId}/${id}/view`, { method: 'PATCH' }).catch(() => {});

    // Load proposal data
    fetch(`${API}/proposals/${tenantId}/${id}/public`)
      .then((r) => {
        if (!r.ok) throw new Error('Proposta não encontrada');
        return r.json();
      })
      .then((data) => {
        setProposal(data);
        if (data.status === 'accepted') setPhase('accepted');
        else if (data.status === 'rejected') setPhase('rejected');
        else setPhase('ready');
      })
      .catch((err) => {
        setErrorMsg(err.message);
        setPhase('error');
      });
  }, [tenantId, id]);

  async function handleAccept() {
    setPhase('accepting');
    try {
      const res = await fetch(`${API}/proposals/${tenantId}/${id}/accept`, { method: 'PATCH' });
      if (!res.ok) throw new Error('Erro ao aceitar proposta');
      setPhase('accepted');
    } catch (err: any) {
      setErrorMsg(err.message);
      setPhase('ready');
    }
  }

  async function handleReject() {
    if (!confirm('Tem certeza que deseja recusar esta proposta?')) return;
    try {
      await fetch(`${API}/proposals/${tenantId}/${id}/reject`, { method: 'PATCH' });
      setPhase('rejected');
    } catch {
      // silently ignore
    }
  }

  if (phase === 'loading') {
    return (
      <div className="min-h-screen bg-[#FAF7F2] flex items-center justify-center">
        <p className="text-[#0E0F12]/50 text-sm">Carregando proposta...</p>
      </div>
    );
  }

  if (phase === 'error') {
    return (
      <div className="min-h-screen bg-[#FAF7F2] flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500 font-medium">{errorMsg || 'Proposta não encontrada'}</p>
          <p className="text-[#0E0F12]/50 text-sm mt-1">Verifique o link e tente novamente.</p>
        </div>
      </div>
    );
  }

  if (phase === 'accepted') {
    return (
      <div className="min-h-screen bg-[#FAF7F2] flex items-center justify-center px-4">
        <div className="bg-white rounded-2xl border border-[#EAE4D9] p-10 text-center max-w-md w-full shadow-sm">
          <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
            <svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-[#0E0F12] mb-2">Proposta aceita!</h2>
          <p className="text-[#0E0F12]/60 text-sm">
            Obrigado, <strong>{proposal?.clientName}</strong>. Sua aceitação foi registrada e em breve você receberá o contrato para assinatura.
          </p>
          {proposal?.tenantName && (
            <p className="text-[#0E0F12]/40 text-xs mt-4">{proposal.tenantName}</p>
          )}
        </div>
      </div>
    );
  }

  if (phase === 'rejected') {
    return (
      <div className="min-h-screen bg-[#FAF7F2] flex items-center justify-center px-4">
        <div className="bg-white rounded-2xl border border-[#EAE4D9] p-10 text-center max-w-md w-full shadow-sm">
          <p className="text-lg font-semibold text-[#0E0F12] mb-2">Proposta recusada</p>
          <p className="text-[#0E0F12]/50 text-sm">Se tiver dúvidas, entre em contato com {proposal?.tenantName ?? 'a empresa'}.</p>
        </div>
      </div>
    );
  }

  const p = proposal!;
  const canAct = ['sent', 'viewed'].includes(p.status);
  const expired = p.validUntil && new Date(p.validUntil + 'T23:59:59') < new Date();

  return (
    <div className="min-h-screen bg-[#FAF7F2] py-10 px-4">
      <div className="max-w-2xl mx-auto space-y-6">

        {/* Header */}
        <div className="bg-white rounded-2xl border border-[#EAE4D9] p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div>
              <p className="text-xs text-[#0E0F12]/40 font-mono">{p.number}</p>
              <h1 className="text-xl font-semibold text-[#0E0F12] mt-0.5">{p.title || 'Proposta Comercial'}</h1>
            </div>
            {p.logoUrl && (
              <img src={p.logoUrl} alt={p.tenantName} className="h-10 object-contain" />
            )}
          </div>
          <div className="flex flex-wrap gap-4 text-sm text-[#0E0F12]/60">
            <span>De: <strong className="text-[#0E0F12]">{p.tenantName}</strong></span>
            <span>Para: <strong className="text-[#0E0F12]">{p.clientName}</strong></span>
            {p.validUntil && (
              <span className={expired ? 'text-red-500' : ''}>
                Válida até: <strong>{fmtDate(p.validUntil)}</strong>
                {expired && ' (expirada)'}
              </span>
            )}
            {p.billingCycle && (
              <span>Ciclo: <strong>{BILLING_LABELS[p.billingCycle] ?? p.billingCycle}</strong></span>
            )}
          </div>
        </div>

        {/* Items */}
        <div className="bg-white rounded-2xl border border-[#EAE4D9] shadow-sm overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-[#FAF7F2] border-b border-[#EAE4D9]">
              <tr>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Item</th>
                <th className="text-right px-6 py-3 font-medium text-[#0E0F12]/60">Qtd</th>
                <th className="text-right px-6 py-3 font-medium text-[#0E0F12]/60">Unitário</th>
                <th className="text-right px-6 py-3 font-medium text-[#0E0F12]/60">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {p.items.map((item, i) => (
                <tr key={i}>
                  <td className="px-6 py-3">
                    <p className="font-medium text-[#0E0F12]">{item.name}</p>
                    {item.description && <p className="text-xs text-[#0E0F12]/50 mt-0.5">{item.description}</p>}
                    {item.billingCycle && (
                      <p className="text-xs text-[#B7895A] mt-0.5">{BILLING_LABELS[item.billingCycle] ?? item.billingCycle}</p>
                    )}
                  </td>
                  <td className="px-6 py-3 text-right text-[#0E0F12]/70">{item.quantity}</td>
                  <td className="px-6 py-3 text-right text-[#0E0F12]/70">{fmt(item.unitPrice)}</td>
                  <td className="px-6 py-3 text-right font-medium text-[#0E0F12]">{fmt(item.total)}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* Totals */}
          <div className="border-t border-[#EAE4D9] px-6 py-4 space-y-1">
            {p.discount > 0 && (
              <>
                <div className="flex justify-between text-sm text-[#0E0F12]/60">
                  <span>Subtotal</span><span>{fmt(p.subtotal)}</span>
                </div>
                <div className="flex justify-between text-sm text-green-600">
                  <span>Desconto</span><span>-{fmt(p.discount)}</span>
                </div>
              </>
            )}
            <div className="flex justify-between text-base font-semibold text-[#0E0F12]">
              <span>Total</span><span>{fmt(p.total)}</span>
            </div>
            {p.paymentTerms && (
              <p className="text-xs text-[#0E0F12]/50 pt-1">Condições: {p.paymentTerms}</p>
            )}
          </div>
        </div>

        {/* Notes */}
        {p.notes && (
          <div className="bg-white rounded-2xl border border-[#EAE4D9] p-6 shadow-sm">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-2">Observações</p>
            <p className="text-sm text-[#0E0F12]/70 whitespace-pre-wrap">{p.notes}</p>
          </div>
        )}

        {/* Actions */}
        {canAct && !expired && (
          <div className="bg-white rounded-2xl border border-[#EAE4D9] p-6 shadow-sm text-center space-y-3">
            <p className="text-sm text-[#0E0F12]/60">Ao aceitar, você concorda com os termos e valores descritos acima.</p>
            <div className="flex gap-3 justify-center">
              <button
                onClick={handleReject}
                className="px-5 py-2.5 rounded-lg border border-[#EAE4D9] text-sm text-[#0E0F12]/60 hover:bg-[#FAF7F2] transition-colors"
              >
                Recusar
              </button>
              <button
                onClick={handleAccept}
                disabled={phase === 'accepting'}
                className="px-6 py-2.5 rounded-lg bg-[#0E0F12] text-white text-sm font-medium hover:bg-[#0E0F12]/80 disabled:opacity-50 transition-colors"
              >
                {phase === 'accepting' ? 'Aguarde...' : 'Aceitar proposta'}
              </button>
            </div>
          </div>
        )}

        {expired && canAct && (
          <div className="bg-red-50 border border-red-200 rounded-2xl p-4 text-center">
            <p className="text-sm text-red-600">Esta proposta expirou em {fmtDate(p.validUntil!)}. Entre em contato com {p.tenantName}.</p>
          </div>
        )}

        <p className="text-center text-xs text-[#0E0F12]/30 pb-4">Powered by Klavo</p>
      </div>
    </div>
  );
}
