"use client";

import { useCallback, useEffect, useState } from "react";

type Profile = {
  userId: string;
  status: string;
  cpfCnpj: string;
  phone: string;
  pixKey: string;
  pixKeyType: string;
  addressStreet: string;
  addressNumber: string;
  addressComplement: string;
  addressNeighborhood: string;
  addressCity: string;
  addressState: string;
  addressZip: string;
  documentIdPath: string;
  documentAddressPath: string;
  rejectionReason: string;
};

const STATUS_LABEL: Record<string, string> = {
  draft: "Rascunho",
  pending: "Em análise",
  approved: "Aprovado",
  rejected: "Recusado",
};

function brl(cents: number) {
  return (cents / 100).toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
}

export default function SellerProfilePanel({ onToast }: { onToast: (m: string) => void }) {
  const [profile, setProfile] = useState<Profile | null>(null);
  const [payouts, setPayouts] = useState<
    { id: string; amountCents: number; status: string; paidAt: string | null; productName?: string }[]
  >([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState<"id" | "address" | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [pRes, payRes] = await Promise.all([
        fetch("/api/seller/profile"),
        fetch("/api/seller/payouts"),
      ]);
      const pData = await pRes.json();
      const payData = await payRes.json();
      if (!pRes.ok) throw new Error(pData.error || "Erro");
      setProfile(pData.profile);
      setPayouts(payData.payouts || []);
    } catch (e) {
      onToast(e instanceof Error ? e.message : "Erro ao carregar");
    } finally {
      setLoading(false);
    }
  }, [onToast]);

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

  async function save() {
    if (!profile) return;
    setSaving(true);
    try {
      const res = await fetch("/api/seller/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          cpfCnpj: profile.cpfCnpj,
          phone: profile.phone,
          pixKey: profile.pixKey,
          pixKeyType: profile.pixKeyType,
          addressStreet: profile.addressStreet,
          addressNumber: profile.addressNumber,
          addressComplement: profile.addressComplement,
          addressNeighborhood: profile.addressNeighborhood,
          addressCity: profile.addressCity,
          addressState: profile.addressState,
          addressZip: profile.addressZip,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro");
      setProfile(data.profile);
      onToast("Dados salvos");
    } catch (e) {
      onToast(e instanceof Error ? e.message : "Erro ao salvar");
    } finally {
      setSaving(false);
    }
  }

  async function submit() {
    setSaving(true);
    try {
      await save();
      const res = await fetch("/api/seller/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "submit" }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro");
      setProfile(data.profile);
      onToast("Cadastro enviado para análise");
    } catch (e) {
      onToast(e instanceof Error ? e.message : "Erro ao enviar");
    } finally {
      setSaving(false);
    }
  }

  async function uploadDoc(kind: "id" | "address", file: File) {
    setUploading(kind);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("kind", kind);
      const res = await fetch("/api/seller/documents", { method: "POST", body: fd });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro");
      setProfile(data.profile);
      onToast("Documento enviado");
    } catch (e) {
      onToast(e instanceof Error ? e.message : "Erro no upload");
    } finally {
      setUploading(null);
    }
  }

  if (loading || !profile) {
    return <p style={{ padding: 24, color: "var(--mut)" }}>Carregando cadastro…</p>;
  }

  const locked = profile.status === "pending" || profile.status === "approved";
  const canEdit = profile.status === "draft" || profile.status === "rejected";

  return (
    <>
      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="ph">
          <h3>Status do cadastro</h3>
          <span className={`tag ${profile.status === "approved" ? "ok" : profile.status === "pending" ? "pend" : profile.status === "rejected" ? "off" : ""} dot`}>
            {STATUS_LABEL[profile.status] || profile.status}
          </span>
        </div>
        {profile.status === "rejected" && profile.rejectionReason ? (
          <p style={{ color: "#f87171", fontSize: ".9rem" }}>
            Motivo: {profile.rejectionReason}
          </p>
        ) : null}
        {profile.status === "approved" ? (
          <p style={{ color: "var(--mut)", fontSize: ".9rem" }}>
            Sua conta está aprovada. Você pode vender e receber repasses via Pix após confirmação do admin.
          </p>
        ) : profile.status === "pending" ? (
          <p style={{ color: "var(--mut)", fontSize: ".9rem" }}>
            Aguarde a análise do administrador. Enquanto isso, o checkout dos seus produtos fica indisponível.
          </p>
        ) : (
          <p style={{ color: "var(--mut)", fontSize: ".9rem" }}>
            Preencha seus dados, chave Pix e envie os documentos. Depois clique em enviar para análise.
          </p>
        )}
      </div>

      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="ph"><h3>Dados pessoais e Pix</h3></div>
        <div className="kv"><label>CPF ou CNPJ</label>
          <input disabled={!canEdit} value={profile.cpfCnpj} onChange={(e) => setProfile({ ...profile, cpfCnpj: e.target.value })} />
        </div>
        <div className="kv"><label>Telefone</label>
          <input disabled={!canEdit} value={profile.phone} onChange={(e) => setProfile({ ...profile, phone: e.target.value })} />
        </div>
        <div className="kv"><label>Tipo da chave Pix</label>
          <select disabled={!canEdit} value={profile.pixKeyType} onChange={(e) => setProfile({ ...profile, pixKeyType: e.target.value })}>
            <option value="cpf">CPF</option>
            <option value="cnpj">CNPJ</option>
            <option value="email">E-mail</option>
            <option value="phone">Telefone</option>
            <option value="random">Chave aleatória</option>
          </select>
        </div>
        <div className="kv"><label>Chave Pix para recebimento</label>
          <input disabled={!canEdit} value={profile.pixKey} onChange={(e) => setProfile({ ...profile, pixKey: e.target.value })} placeholder="Sua chave Pix" />
        </div>
      </div>

      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="ph"><h3>Endereço</h3></div>
        <div className="kv"><label>CEP</label>
          <input disabled={!canEdit} value={profile.addressZip} onChange={(e) => setProfile({ ...profile, addressZip: e.target.value })} />
        </div>
        <div className="kv"><label>Rua</label>
          <input disabled={!canEdit} value={profile.addressStreet} onChange={(e) => setProfile({ ...profile, addressStreet: e.target.value })} />
        </div>
        <div className="kv"><label>Número</label>
          <input disabled={!canEdit} value={profile.addressNumber} onChange={(e) => setProfile({ ...profile, addressNumber: e.target.value })} />
        </div>
        <div className="kv"><label>Complemento</label>
          <input disabled={!canEdit} value={profile.addressComplement} onChange={(e) => setProfile({ ...profile, addressComplement: e.target.value })} />
        </div>
        <div className="kv"><label>Bairro</label>
          <input disabled={!canEdit} value={profile.addressNeighborhood} onChange={(e) => setProfile({ ...profile, addressNeighborhood: e.target.value })} />
        </div>
        <div className="kv"><label>Cidade</label>
          <input disabled={!canEdit} value={profile.addressCity} onChange={(e) => setProfile({ ...profile, addressCity: e.target.value })} />
        </div>
        <div className="kv"><label>UF</label>
          <input disabled={!canEdit} maxLength={2} value={profile.addressState} onChange={(e) => setProfile({ ...profile, addressState: e.target.value.toUpperCase() })} />
        </div>
      </div>

      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="ph"><h3>Documentos</h3></div>
        <div className="seller-doc-row">
          <div>
            <b>Documento de identidade</b>
            {profile.documentIdPath ? (
              <a href={`/api/seller/documents?path=${encodeURIComponent(profile.documentIdPath)}`} target="_blank" rel="noreferrer">Ver enviado</a>
            ) : (
              <span style={{ color: "var(--mut)" }}>Não enviado</span>
            )}
          </div>
          {canEdit ? (
            <label className="b ghost sm">
              {uploading === "id" ? "Enviando…" : "Enviar"}
              <input type="file" accept="image/*,application/pdf" hidden onChange={(e) => e.target.files?.[0] && uploadDoc("id", e.target.files[0])} />
            </label>
          ) : null}
        </div>
        <div className="seller-doc-row">
          <div>
            <b>Comprovante de endereço</b>
            {profile.documentAddressPath ? (
              <a href={`/api/seller/documents?path=${encodeURIComponent(profile.documentAddressPath)}`} target="_blank" rel="noreferrer">Ver enviado</a>
            ) : (
              <span style={{ color: "var(--mut)" }}>Não enviado</span>
            )}
          </div>
          {canEdit ? (
            <label className="b ghost sm">
              {uploading === "address" ? "Enviando…" : "Enviar"}
              <input type="file" accept="image/*,application/pdf" hidden onChange={(e) => e.target.files?.[0] && uploadDoc("address", e.target.files[0])} />
            </label>
          ) : null}
        </div>
      </div>

      {canEdit ? (
        <div style={{ display: "flex", gap: 10, marginBottom: 24 }}>
          <button type="button" className="b ghost" disabled={saving} onClick={save}>Salvar rascunho</button>
          <button type="button" className="b lime" disabled={saving} onClick={submit}>
            {saving ? "Enviando…" : "Enviar para análise"}
          </button>
        </div>
      ) : null}

      <div className="panel">
        <div className="ph"><h3>Meus repasses</h3></div>
        {payouts.length === 0 ? (
          <p style={{ color: "var(--mut)", padding: "8px 0" }}>Nenhum repasse ainda.</p>
        ) : (
          <table className="tbl">
            <thead>
              <tr><th>Produto</th><th>Valor</th><th>Status</th><th>Pago em</th></tr>
            </thead>
            <tbody>
              {payouts.map((p) => (
                <tr key={p.id}>
                  <td>{p.productName || "—"}</td>
                  <td>{brl(p.amountCents)}</td>
                  <td><span className={`tag ${p.status === "paid" ? "ok" : "pend"} dot`}>{p.status}</span></td>
                  <td style={{ color: "var(--mut)" }}>{p.paidAt ? new Date(p.paidAt).toLocaleString("pt-BR") : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </>
  );
}
