'use client';

import { useEffect, useState, FormEvent } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import ServiceListSelect from '@/components/service-list-select';
import api from '@/lib/api';
import { Proposal, Client, Product } from '@/types';

const STATUS_COLORS: Record<string, string> = {
  draft:    'bg-[#EAE4D9] text-[#0E0F12]/60',
  sent:     'bg-blue-100 text-blue-700',
  viewed:   'bg-purple-100 text-purple-700',
  accepted: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
};
const STATUS_LABELS: Record<string, string> = {
  draft: 'Rascunho', sent: 'Enviada', viewed: 'Visualizada',
  accepted: 'Aceita', rejected: 'Recusada',
};
const BILLING_LABELS: Record<string, string> = {
  monthly: 'Mensal', yearly: 'Anual', once: 'Avulso', hourly: 'Por hora',
};

interface ItemForm {
  productId: string;
  productVariantId: string;
  name: string;
  description: string;
  billingCycle: string;
  unitPrice: string;
  quantity: string;
  discount: string;
  serviceListItem: string;
  issAliquota: string;
  discrimination: string;
  billingType: 'fixed' | 'measurement';
  includedQty: string;
  measurementUnit: string;
  excessPricing: 'negotiated' | 'table';
}

const EMPTY_ITEM: ItemForm = {
  productId: '', productVariantId: '', name: '', description: '',
  billingCycle: 'monthly', unitPrice: '', quantity: '1', discount: '0',
  serviceListItem: '', issAliquota: '', discrimination: '',
  billingType: 'fixed', includedQty: '', measurementUnit: 'horas', excessPricing: 'negotiated',
};

const EMPTY_FORM = {
  clientId: '', title: '', validUntil: '', billingCycle: 'monthly',
  paymentTermsType: '30d', paymentTermsDay: '5', paymentTermsCustom: '',
  notes: '', internalNotes: '',
};

function resolvePaymentTerms(type: string, day: string, custom: string): string | undefined {
  if (type === 'cash')      return 'À vista';
  if (type === '30d')       return '30 dias após aprovação';
  if (type === '60d')       return '60 dias após aprovação';
  if (type === '90d')       return '90 dias após aprovação';
  if (type === 'fixed_day') return `Dia ${day} do mês`;
  return custom || undefined;
}

function calcItemTotal(item: ItemForm) {
  const price = Number(item.unitPrice) || 0;
  const qty   = Number(item.quantity)  || 1;
  const disc  = Number(item.discount)  || 0;
  return Math.max(0, price * qty - disc);
}

export default function PropostasPage() {
  const [items, setItems]       = useState<Proposal[]>([]);
  const [clients, setClients]   = useState<Client[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading]   = useState(true);
  const [open, setOpen]         = useState(false);
  const [form, setForm]         = useState(EMPTY_FORM);
  const [lineItems, setLineItems] = useState<ItemForm[]>([{ ...EMPTY_ITEM }]);
  const [saving, setSaving]     = useState(false);
  const [error, setError]       = useState('');
  const [sending, setSending]   = useState<string | null>(null);
  const [copied, setCopied]     = useState<string | null>(null);

  function proposalLink(p: Proposal) {
    const base = typeof window !== 'undefined' ? window.location.origin : '';
    return `${base}/p/${(p as any).tenantId}/${p.id}`;
  }

  async function handleSend(p: Proposal) {
    if (!confirm(`Marcar proposta ${p.number} como enviada?`)) return;
    setSending(p.id);
    try {
      await api.patch(`/proposals/${p.id}/send`);
      load();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao enviar');
    } finally {
      setSending(null);
    }
  }

  function copyLink(p: Proposal) {
    navigator.clipboard.writeText(proposalLink(p));
    setCopied(p.id);
    setTimeout(() => setCopied(null), 2000);
  }

  function load() {
    setLoading(true);
    api.get('/proposals').then((r) => setItems(r.data.data ?? r.data)).catch(() => {}).finally(() => setLoading(false));
  }

  useEffect(() => {
    load();
    api.get('/clients').then((r) => setClients(r.data.data ?? r.data)).catch(() => {});
    api.get('/products').then((r) => setProducts(r.data.data ?? r.data)).catch(() => {});
  }, []);

  function openModal() {
    setForm(EMPTY_FORM);
    setLineItems([{ ...EMPTY_ITEM }]);
    setError('');
    setOpen(true);
  }

  function setF(field: string, value: string) { setForm((p) => ({ ...p, [field]: value })); }

  function setItem(idx: number, field: keyof ItemForm, value: string) {
    setLineItems((prev) => prev.map((it, i) => i === idx ? { ...it, [field]: value } : it));
  }

  function onProductSelect(idx: number, productId: string) {
    const prod = products.find((p) => p.id === productId) as any;
    if (!prod) { setItem(idx, 'productId', ''); return; }
    const variant = prod.variants?.[0];
    setLineItems((prev) => prev.map((it, i) => i !== idx ? it : {
      ...it,
      productId,
      productVariantId: variant?.id ?? '',
      name:             variant?.name ?? prod.name,
      billingCycle:     variant?.billingCycle ?? 'monthly',
      unitPrice:        String(variant?.price ?? ''),
      serviceListItem:  prod.serviceListItem ?? '',
      issAliquota:      prod.issAliquota != null ? String(prod.issAliquota) : '',
      discrimination:   prod.discrimination ?? '',
    }));
  }

  function onVariantSelect(idx: number, variantId: string) {
    const item = lineItems[idx];
    const prod = products.find((p) => p.id === item.productId) as any;
    const variant = prod?.variants?.find((v: any) => v.id === variantId);
    if (!variant) return;
    setLineItems((prev) => prev.map((it, i) => i !== idx ? it : {
      ...it,
      productVariantId: variant.id,
      name:             variant.name,
      billingCycle:     variant.billingCycle,
      unitPrice:        String(variant.price),
    }));
  }

  function addItem() { setLineItems((p) => [...p, { ...EMPTY_ITEM }]); }
  function removeItem(idx: number) { setLineItems((p) => p.filter((_, i) => i !== idx)); }

  const grandTotal = lineItems.reduce((acc, it) => acc + calcItemTotal(it), 0);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (lineItems.length === 0) { setError('Adicione ao menos um produto.'); return; }
    setError('');
    setSaving(true);
    try {
      const payload = {
        clientId:     form.clientId,
        title:        form.title || undefined,
        validUntil:   form.validUntil || undefined,
        billingCycle: form.billingCycle,
        paymentTerms: resolvePaymentTerms(form.paymentTermsType, form.paymentTermsDay, form.paymentTermsCustom),
        notes:        form.notes || undefined,
        internalNotes: form.internalNotes || undefined,
        items: lineItems.map((it, idx) => ({
          productId:        it.productId || undefined,
          productVariantId: it.productVariantId || undefined,
          name:             it.name,
          description:      it.description || undefined,
          billingCycle:     it.billingCycle,
          unitPrice:        Number(it.unitPrice),
          quantity:         Number(it.quantity) || 1,
          discount:         Number(it.discount) || 0,
          serviceListItem:  it.serviceListItem || undefined,
          issAliquota:      it.issAliquota ? Number(it.issAliquota) : undefined,
          discrimination:   it.discrimination || undefined,
          billingType:      it.billingType,
          includedQty:      it.billingType === 'measurement' && it.includedQty ? Number(it.includedQty) : undefined,
          measurementUnit:  it.billingType === 'measurement' ? it.measurementUnit : undefined,
          excessPricing:    it.billingType === 'measurement' ? it.excessPricing : undefined,
          sortOrder:        idx,
        })),
      };
      await api.post('/proposals', payload);
      setOpen(false);
      load();
    } catch (err: any) {
      setError(err.response?.data?.message ?? 'Erro ao salvar proposta');
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Header
        title="Propostas"
        subtitle="Gerencie propostas comerciais"
        action={<button className="btn-primary" onClick={openModal}>+ Nova proposta</button>}
      />

      <div className="bg-white rounded-xl border border-[#EAE4D9] overflow-x-auto">
        {loading ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Carregando...</p>
        ) : items.length === 0 ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Nenhuma proposta criada ainda.</p>
        ) : (
          <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">Número</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Título</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Ciclo</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Total</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="px-6 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((p) => (
                <tr key={p.id} className={`hover:bg-[#FAF7F2] ${p.status === 'rejected' ? 'opacity-50' : ''}`}>
                  <td className="px-6 py-3 font-medium text-[#0E0F12] font-mono text-xs">{p.number}</td>
                  <td className="px-6 py-3 text-[#0E0F12]">{p.title ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{BILLING_LABELS[(p as any).billingCycle] ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12] font-medium">R$ {Number(p.total).toFixed(2)}</td>
                  <td className="px-6 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[p.status] ?? 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>
                      {STATUS_LABELS[p.status] ?? p.status}
                    </span>
                  </td>
                  <td className="px-6 py-3 text-right space-x-3 whitespace-nowrap">
                    <button
                      onClick={() => copyLink(p)}
                      className="text-xs font-medium text-[#0E0F12]/40 hover:text-[#0E0F12] transition-colors"
                    >
                      {copied === p.id ? 'Copiado!' : 'Copiar link'}
                    </button>
                    {['draft', 'rejected'].includes(p.status) && (
                      <button
                        onClick={() => handleSend(p)}
                        disabled={sending === p.id}
                        className="text-xs font-medium text-[#B7895A] hover:text-[#B7895A]/70 disabled:opacity-50 transition-colors"
                      >
                        {sending === p.id ? '...' : 'Enviar'}
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Wide modal for proposal creation */}
      <Modal open={open} onClose={() => setOpen(false)} title="Nova proposta" wide>
        <form onSubmit={handleSubmit} className="space-y-5">
          {error && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{error}</div>}

          {/* Header section */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Cliente <span className="text-red-500">*</span></label>
              <select className="input" required value={form.clientId} onChange={(e) => setF('clientId', e.target.value)}>
                <option value="">Selecione o cliente...</option>
                {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Título da proposta</label>
              <input className="input" value={form.title} onChange={(e) => setF('title', e.target.value)} placeholder="Proposta de serviços — Maio 2025" />
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Válida até</label>
              <input className="input" type="date" value={form.validUntil} onChange={(e) => setF('validUntil', e.target.value)} />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Ciclo de cobrança</label>
              <select className="input" value={form.billingCycle} onChange={(e) => setF('billingCycle', e.target.value)}>
                <option value="monthly">Mensal</option>
                <option value="yearly">Anual</option>
                <option value="once">Avulso</option>
                <option value="hourly">Por hora</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Condição de pagamento</label>
              <select className="input" value={form.paymentTermsType} onChange={(e) => setF('paymentTermsType', e.target.value)}>
                <option value="cash">À vista</option>
                <option value="30d">30 dias após aprovação</option>
                <option value="60d">60 dias após aprovação</option>
                <option value="90d">90 dias após aprovação</option>
                <option value="fixed_day">Dia fixo do mês</option>
                <option value="custom">Outro</option>
              </select>
              {form.paymentTermsType === 'fixed_day' && (
                <div className="mt-2 flex items-center gap-2">
                  <span className="text-sm text-[#0E0F12]/60">Dia</span>
                  <input
                    className="input w-20"
                    type="number"
                    min="1"
                    max="31"
                    value={form.paymentTermsDay}
                    onChange={(e) => setF('paymentTermsDay', e.target.value)}
                  />
                  <span className="text-sm text-[#0E0F12]/60">do mês</span>
                </div>
              )}
              {form.paymentTermsType === 'custom' && (
                <input
                  className="input mt-2"
                  value={form.paymentTermsCustom}
                  onChange={(e) => setF('paymentTermsCustom', e.target.value)}
                  placeholder="Descreva a condição de pagamento"
                />
              )}
            </div>
          </div>

          {/* Items */}
          <div className="border-t border-[#EAE4D9] pt-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide">Produtos / serviços</p>
              <button type="button" onClick={addItem} className="text-xs text-[#B7895A] hover:text-[#9E7248] font-medium">+ Adicionar item</button>
            </div>

            <div className="space-y-4">
              {lineItems.map((item, idx) => (
                <div key={idx} className="border border-[#EAE4D9] rounded-xl p-4 space-y-3 bg-[#FAF7F2]">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-semibold text-[#0E0F12]/50">Item {idx + 1}</span>
                    {lineItems.length > 1 && (
                      <button type="button" onClick={() => removeItem(idx)} className="text-xs text-red-400 hover:text-red-600">Remover</button>
                    )}
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Produto (catálogo)</label>
                      <select className="input text-sm" value={item.productId} onChange={(e) => onProductSelect(idx, e.target.value)}>
                        <option value="">Selecionar produto...</option>
                        {products.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
                      </select>
                    </div>
                    {(() => {
                      const selectedProduct = products.find((p) => p.id === item.productId) as any;
                      const variantOptions = selectedProduct?.variants ?? [];
                      if (!item.productId || variantOptions.length < 2) return (
                        <div>
                          <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Nome do item <span className="text-red-500">*</span></label>
                          <input className="input text-sm" required minLength={2} value={item.name} onChange={(e) => setItem(idx, 'name', e.target.value)} placeholder="Descrição do serviço" />
                        </div>
                      );
                      return (
                        <div>
                          <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Variação / Plano</label>
                          <select className="input text-sm" value={item.productVariantId} onChange={(e) => onVariantSelect(idx, e.target.value)}>
                            {variantOptions.map((v: any) => (
                              <option key={v.id} value={v.id}>
                                {v.name} — R$ {Number(v.price).toFixed(2)}
                              </option>
                            ))}
                          </select>
                        </div>
                      );
                    })()}
                  </div>

                  {(() => {
                    const selectedProduct = products.find((p) => p.id === item.productId) as any;
                    const hasMultipleVariants = (selectedProduct?.variants?.length ?? 0) >= 2;
                    if (!hasMultipleVariants) return null;
                    return (
                      <div>
                        <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Nome do item <span className="text-red-500">*</span></label>
                        <input className="input text-sm" required minLength={2} value={item.name} onChange={(e) => setItem(idx, 'name', e.target.value)} placeholder="Descrição do serviço" />
                      </div>
                    );
                  })()}

                  <div className="grid grid-cols-3 gap-3">
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Preço unitário (R$) <span className="text-red-500">*</span></label>
                      <input className="input text-sm" type="number" required min="0" step="0.01" value={item.unitPrice} onChange={(e) => setItem(idx, 'unitPrice', e.target.value)} placeholder="1500.00" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Ciclo deste item</label>
                      <select className="input text-sm" value={item.billingCycle} onChange={(e) => setItem(idx, 'billingCycle', e.target.value)}>
                        <option value="monthly">Mensal</option>
                        <option value="yearly">Anual</option>
                        <option value="once">Avulso</option>
                        <option value="hourly">Por hora</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Desconto (R$)</label>
                      <input className="input text-sm" type="number" min="0" step="0.01" value={item.discount} onChange={(e) => setItem(idx, 'discount', e.target.value)} placeholder="0.00" />
                    </div>
                  </div>

                  {/* Billing type toggle */}
                  <div>
                    <label className="block text-xs font-medium text-[#0E0F12]/60 mb-2">Tipo de cobrança</label>
                    <div className="flex gap-3">
                      {(['fixed', 'measurement'] as const).map((bt) => (
                        <label key={bt} className={`flex items-center gap-2 px-3 py-2 rounded-lg border cursor-pointer text-sm transition-colors ${item.billingType === bt ? 'border-[#B7895A] bg-[#EAE4D9] text-[#0E0F12] font-medium' : 'border-[#EAE4D9] text-[#0E0F12]/60'}`}>
                          <input type="radio" className="sr-only" checked={item.billingType === bt} onChange={() => setItem(idx, 'billingType', bt)} />
                          {bt === 'fixed' ? 'Valor fixo' : 'Por medição / uso'}
                        </label>
                      ))}
                    </div>
                  </div>

                  {item.billingType === 'fixed' && (
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Quantidade</label>
                        <input className="input text-sm" type="number" min="0" step="0.001" value={item.quantity} onChange={(e) => setItem(idx, 'quantity', e.target.value)} />
                      </div>
                      <div className="flex items-end pb-1">
                        <span className="text-sm text-[#0E0F12] font-medium">Total: R$ {calcItemTotal(item).toFixed(2)}</span>
                      </div>
                    </div>
                  )}

                  {item.billingType === 'measurement' && (
                    <div className="grid grid-cols-3 gap-3">
                      <div>
                        <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Qtd incluída na faixa</label>
                        <input className="input text-sm" type="number" min="0" step="0.001" value={item.includedQty} onChange={(e) => setItem(idx, 'includedQty', e.target.value)} placeholder="10" />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Unidade de medição</label>
                        <input className="input text-sm" value={item.measurementUnit} onChange={(e) => setItem(idx, 'measurementUnit', e.target.value)} placeholder="horas" />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-[#0E0F12]/60 mb-1">Excedente</label>
                        <select className="input text-sm" value={item.excessPricing} onChange={(e) => setItem(idx, 'excessPricing', e.target.value as any)}>
                          <option value="negotiated">Preço negociado</option>
                          <option value="table">Preço de tabela</option>
                        </select>
                      </div>
                    </div>
                  )}

                  {/* Fiscal fields */}
                  <div className="grid grid-cols-2 gap-3 pt-1 border-t border-[#EAE4D9]">
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/50 mb-1">Item lista serviços (LC116)</label>
                      <ServiceListSelect value={item.serviceListItem} onChange={(v) => setItem(idx, 'serviceListItem', v)} />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-[#0E0F12]/50 mb-1">Alíquota ISS (%)</label>
                      <input className="input text-sm" type="number" min="0" max="100" step="0.01" value={item.issAliquota} onChange={(e) => setItem(idx, 'issAliquota', e.target.value)} placeholder="5.00" />
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div className="flex justify-end pt-3">
              <p className="text-sm font-semibold text-[#0E0F12]">Total da proposta: R$ {grandTotal.toFixed(2)}</p>
            </div>
          </div>

          {/* Notes */}
          <div className="grid grid-cols-2 gap-4 border-t border-[#EAE4D9] pt-4">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Observações (visível ao cliente)</label>
              <textarea className="input resize-none" rows={3} value={form.notes} onChange={(e) => setF('notes', e.target.value)} placeholder="Condições especiais, observações..." />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Notas internas</label>
              <textarea className="input resize-none" rows={3} value={form.internalNotes} onChange={(e) => setF('internalNotes', e.target.value)} placeholder="Notas para uso interno..." />
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Salvando...' : 'Criar proposta'}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}
