"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  AlertCircle,
  ArrowRight,
  CheckCircle2,
  CircleDollarSign,
  Clock3,
  History,
  Landmark,
  ListChecks,
  Percent,
  Settings2,
  ShieldCheck,
  Sparkles,
  Wallet,
} from "lucide-react";
import { PageHeader } from "@/components/ui/page-header";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { canCompany, getCompanyContext, getEffectiveCompanyRole } from "@/lib/company-context";
import { getSupabaseClient } from "@/lib/supabase";

type PlanRule = {
  id: string;
  name: string;
  percent_value: number | null;
};

type PlanAssignment = {
  id: string;
  target_type: string;
  target_user_id: string | null;
  target_role: string | null;
};

type PlanVersion = {
  id: string;
  version_number: number;
  status: string;
  effective_from: string;
  rules: PlanRule[];
  assignments: PlanAssignment[];
};

type CommissionPlan = {
  id: string;
  name: string;
  description: string | null;
  status: string;
  created_at: string;
  versions: PlanVersion[];
};

type CommissionEvent = {
  id: string;
  seller_user_id: string;
  seller_email: string | null;
  seller_role: string | null;
  order_number: number | null;
  source_date: string;
  event_type: string;
  status: string;
  gross_basis_amount: number;
  commission_percent: number | null;
  commission_amount: number;
  notes: string | null;
};

type CommissionPeriod = {
  id: string;
  period_label: string;
  start_date: string;
  end_date: string;
  status: string;
  closed_at: string | null;
  approved_at: string | null;
  created_at: string;
  updated_at: string;
};

type CommissionPayout = {
  id: string;
  period_id: string;
  seller_user_id: string;
  seller_email: string | null;
  seller_role: string | null;
  gross_amount: number;
  adjustments_amount: number;
  net_amount: number;
  status: string;
  accounts_payable_id: string | null;
  created_at: string;
  updated_at: string;
  period:
    | {
        id: string;
        period_label: string;
        start_date: string;
        end_date: string;
        status: string;
      }
    | null;
  payable:
    | {
        id: string;
        description: string;
        due_date: string | null;
        payment_date: string | null;
        status: string;
        amount: number;
      }
    | null;
};

type CommissionStatementItem = {
  id: string;
  period_id: string;
  seller_user_id: string;
  event_id: string | null;
  statement_type: string;
  amount: number;
  included_in_payout: boolean;
  created_at: string;
  period:
    | {
        id: string;
        period_label: string;
        start_date: string;
        end_date: string;
        status: string;
      }
    | null;
  event:
    | {
        id: string;
        order_id: string | null;
        payment_id: string | null;
        source_date: string;
        status: string;
        commission_percent: number | null;
        commission_amount: number;
        notes: string | null;
      }
    | null;
  seller_email: string | null;
  seller_role: string | null;
};

type CommissionStatementResponse = {
  summary: {
    total_amount: number;
    payout_eligible_amount: number;
    item_count: number;
  };
  items: CommissionStatementItem[];
};

type CommissionAuditLog = {
  id: string;
  entity_type: string;
  entity_id: string;
  action: string;
  reason: string | null;
  actor_user_id: string | null;
  actor_email: string | null;
  actor_role: string | null;
  created_at: string;
};

type PayoutUser = {
  user_id: string;
  email: string;
  role: string;
};

type PayoutProfile = {
  id?: string;
  user_id: string;
  holder_name: string | null;
  document_type: string | null;
  document_number: string | null;
  payout_method: string;
  pix_key_type: string | null;
  pix_key: string | null;
  bank_name: string | null;
  bank_code: string | null;
  agency_number: string | null;
  agency_digit: string | null;
  account_number: string | null;
  account_digit: string | null;
  account_type: string | null;
  notes: string | null;
  active: boolean;
};

type PayoutProfilesResponse = {
  users: PayoutUser[];
  profiles: PayoutProfile[];
};

type PlanFormState = {
  name: string;
  description: string;
  effective_from: string;
  percent_value: string;
  target_type: "company_default" | "role" | "user";
  target_role: string;
  target_user_id: string;
};

type ProfileFormState = {
  holder_name: string;
  document_type: string;
  document_number: string;
  payout_method: string;
  pix_key_type: string;
  pix_key: string;
  bank_name: string;
  bank_code: string;
  agency_number: string;
  agency_digit: string;
  account_number: string;
  account_digit: string;
  account_type: string;
  notes: string;
  active: boolean;
};

type PeriodFormState = {
  start_date: string;
  end_date: string;
  period_label: string;
  due_date: string;
  reopen_reason: string;
};

type AdjustmentFormState = {
  event_id: string;
  amount: string;
  reason: string;
};

const ROLE_OPTIONS = [
  { value: "sales", label: "Vendas" },
  { value: "manager", label: "Gerente" },
  { value: "financial", label: "Financeiro" },
  { value: "production", label: "Produção" },
  { value: "viewer", label: "Visualizador" },
  { value: "admin", label: "Admin" },
];

function formatCurrency(value: number) {
  return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(Number(value || 0));
}

function formatDate(value: string | null | undefined) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return new Intl.DateTimeFormat("pt-BR").format(date);
}

function translateStatus(status: string | null | undefined) {
  switch (status) {
    case "calculated":
      return "Pronto para fechar";
    case "pending_source":
      return "Falta configurar";
    case "blocked":
      return "Precisa revisar";
    case "reversed":
      return "Estornado";
    case "closed":
      return "Fechado";
    case "paid":
      return "Pago";
    case "approved":
      return "Aprovado";
    case "payable_created":
      return "Conta criada";
    case "partially_paid":
      return "Pago em parte";
    case "reopened":
      return "Reaberto";
    case "draft":
      return "Rascunho";
    case "published":
      return "Publicado";
    case "active":
      return "Ativo";
    case "inactive":
      return "Inativo";
    case "archived":
      return "Arquivado";
    case "PENDING":
      return "Aguardando pagamento";
    case "PAID":
      return "Pago";
    case "CANCELED":
      return "Cancelado";
    default:
      return status || "-";
  }
}

function translateStatementType(type: string | null | undefined) {
  switch (type) {
    case "event":
      return "Comissão";
    case "adjustment":
      return "Ajuste";
    case "carry_over":
      return "Saldo anterior";
    default:
      return type || "-";
  }
}

function translateTarget(
  assignment:
    | {
        target_type: string;
        target_role: string | null;
      }
    | undefined
) {
  if (!assignment) return "Não definido";
  if (assignment.target_type === "user") return "Pessoa específica";
  if (assignment.target_type === "role") return `Cargo: ${assignment.target_role || "-"}`;
  return "Toda a empresa";
}

function translateRole(role: string | null | undefined) {
  switch (role) {
    case "sales":
      return "Vendas";
    case "manager":
      return "Gerente";
    case "financial":
      return "Financeiro";
    case "production":
      return "Produção";
    case "viewer":
      return "Visualizador";
    case "admin":
      return "Administrador";
    case "owner":
      return "Proprietário";
    default:
      return role || "-";
  }
}

function translateAuditEntityType(type: string | null | undefined) {
  switch (type) {
    case "commission_event":
      return "Lançamento de comissão";
    case "commission_period":
      return "Período de comissão";
    case "commission_payout":
      return "Pagamento de comissão";
    case "commission_adjustment":
      return "Ajuste de comissão";
    case "commission_plan":
      return "Regra de comissão";
    default:
      return type || "-";
  }
}

function translateAuditAction(action: string | null | undefined) {
  switch (action) {
    case "generated_from_payment":
      return "Comissão gerada pelo recebimento";
    case "reversed_from_payment":
      return "Comissão estornada pelo recebimento";
    case "closed":
      return "Período fechado";
    case "approved":
      return "Período aprovado";
    case "reopened":
      return "Período reaberto";
    case "payable_created":
      return "Pagamento criado";
    case "adjusted":
      return "Ajuste manual realizado";
    case "created":
      return "Criado";
    case "updated":
      return "Atualizado";
    default:
      return action || "-";
  }
}

function translateAuditReason(reason: string | null | undefined) {
  if (!reason) return "";

  return reason
    .replaceAll("Payout", "pagamento")
    .replaceAll("payout", "pagamento")
    .replaceAll("owner", "proprietário")
    .replaceAll("sales", "vendas");
}

function getStatusTone(status: string | null | undefined) {
  switch (status) {
    case "paid":
    case "PAID":
    case "approved":
    case "active":
      return "bg-emerald-50 text-emerald-700 border border-emerald-200";
    case "pending_source":
    case "PENDING":
    case "draft":
    case "reopened":
      return "bg-amber-50 text-amber-700 border border-amber-200";
    case "blocked":
    case "reversed":
    case "CANCELED":
      return "bg-rose-50 text-rose-700 border border-rose-200";
    default:
      return "bg-slate-100 text-slate-700 border border-slate-200";
  }
}

function emptyProfileForm(): ProfileFormState {
  return {
    holder_name: "",
    document_type: "cpf",
    document_number: "",
    payout_method: "pix",
    pix_key_type: "cpf",
    pix_key: "",
    bank_name: "",
    bank_code: "",
    agency_number: "",
    agency_digit: "",
    account_number: "",
    account_digit: "",
    account_type: "checking",
    notes: "",
    active: true,
  };
}

async function fetchJson<T>(url: string, init?: RequestInit) {
  const response = await fetch(url, {
    ...init,
    headers: {
      "content-type": "application/json",
      ...(init?.headers ?? {}),
    },
    cache: "no-store",
  });
  const json = (await response.json().catch(() => null)) as (T & { error?: string; message?: string }) | null;
  if (!response.ok) {
    throw new Error(json?.error || "Falha ao carregar dados de comissão.");
  }
  return json as T;
}

export default function FinancialCommissionsPageClient() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [plans, setPlans] = useState<CommissionPlan[]>([]);
  const [events, setEvents] = useState<CommissionEvent[]>([]);
  const [periods, setPeriods] = useState<CommissionPeriod[]>([]);
  const [payouts, setPayouts] = useState<CommissionPayout[]>([]);
  const [statementData, setStatementData] = useState<CommissionStatementResponse>({
    summary: { total_amount: 0, payout_eligible_amount: 0, item_count: 0 },
    items: [],
  });
  const [auditLogs, setAuditLogs] = useState<CommissionAuditLog[]>([]);
  const [profileData, setProfileData] = useState<PayoutProfilesResponse>({ users: [], profiles: [] });
  const [selectedUserId, setSelectedUserId] = useState("");
  const [selectedEventStatus, setSelectedEventStatus] = useState("");
  const [selectedAuditEntityType, setSelectedAuditEntityType] = useState("");
  const [activeTab, setActiveTab] = useState("comecar");
  const [planForm, setPlanForm] = useState<PlanFormState>({
    name: "",
    description: "",
    effective_from: new Date().toISOString().slice(0, 10),
    percent_value: "5,00",
    target_type: "company_default",
    target_role: "sales",
    target_user_id: "",
  });
  const [profileForm, setProfileForm] = useState<ProfileFormState>(emptyProfileForm);
  const [periodForm, setPeriodForm] = useState<PeriodFormState>({
    start_date: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10),
    end_date: new Date().toISOString().slice(0, 10),
    period_label: "",
    due_date: new Date().toISOString().slice(0, 10),
    reopen_reason: "",
  });
  const [adjustmentForm, setAdjustmentForm] = useState<AdjustmentFormState>({
    event_id: "",
    amount: "",
    reason: "",
  });
  const [selectedPeriodId, setSelectedPeriodId] = useState("");
  const [planMessage, setPlanMessage] = useState("");
  const [profileMessage, setProfileMessage] = useState("");
  const [periodMessage, setPeriodMessage] = useState("");
  const [adjustmentMessage, setAdjustmentMessage] = useState("");
  const [savingPlan, setSavingPlan] = useState(false);
  const [savingProfile, setSavingProfile] = useState(false);
  const [savingPeriodAction, setSavingPeriodAction] = useState(false);
  const [savingAdjustment, setSavingAdjustment] = useState(false);
  const [showMyViewShortcut, setShowMyViewShortcut] = useState(false);
  const [error, setError] = useState("");

  const loadAll = useCallback(async () => {
    try {
      setLoading(true);
      setError("");
      const [plansRes, eventsRes, profilesRes, periodsRes, payoutsRes, auditRes] = await Promise.all([
        fetchJson<{ plans: CommissionPlan[] }>("/api/commissions/plans"),
        fetchJson<{ events: CommissionEvent[] }>("/api/commissions/events"),
        fetchJson<PayoutProfilesResponse>("/api/commissions/payout-profiles"),
        fetchJson<{ periods: CommissionPeriod[] }>("/api/commissions/periods"),
        fetchJson<{ payouts: CommissionPayout[] }>("/api/commissions/payouts"),
        fetchJson<{ logs: CommissionAuditLog[] }>("/api/commissions/audit"),
      ]);
      setPlans(plansRes.plans || []);
      setEvents(eventsRes.events || []);
      setProfileData(profilesRes);
      setPeriods(periodsRes.periods || []);
      setPayouts(payoutsRes.payouts || []);
      setAuditLogs(auditRes.logs || []);
      setSelectedUserId((prev) => prev || profilesRes.users[0]?.user_id || "");
      setSelectedPeriodId((prev) => prev || periodsRes.periods?.[0]?.id || "");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Falha ao carregar dados de comissão.");
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    let cancelled = false;

    async function loadMyViewAccess() {
      try {
        const supabase = getSupabaseClient();
        const {
          data: { user },
        } = await supabase.auth.getUser();

        if (!user) {
          if (!cancelled) setShowMyViewShortcut(false);
          return;
        }

        const ctx = await getCompanyContext(supabase, user);
        const role = getEffectiveCompanyRole(ctx, user.id);
        const canOpenMyView = canCompany(ctx, user.id, "commissions.self");
        const isAdminOrOwner = role === "admin" || role === "owner";

        if (!cancelled) {
          setShowMyViewShortcut(isAdminOrOwner && canOpenMyView);
        }
      } catch {
        if (!cancelled) setShowMyViewShortcut(false);
      }
    }

    loadMyViewAccess();

    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    const controller = new AbortController();

    const loadStatement = async () => {
      try {
        const params = new URLSearchParams();
        if (selectedUserId) params.set("seller_user_id", selectedUserId);
        if (selectedPeriodId) params.set("period_id", selectedPeriodId);
        const result = await fetchJson<CommissionStatementResponse>(`/api/commissions/statement?${params.toString()}`, {
          signal: controller.signal,
        });
        setStatementData(result);
      } catch {
        if (controller.signal.aborted) return;
        setStatementData({
          summary: { total_amount: 0, payout_eligible_amount: 0, item_count: 0 },
          items: [],
        });
      }
    };

    if (selectedUserId || selectedPeriodId) {
      loadStatement();
    }

    return () => controller.abort();
  }, [selectedPeriodId, selectedUserId]);

  const selectedProfile = useMemo(
    () => profileData.profiles.find((profile) => profile.user_id === selectedUserId) || null,
    [profileData.profiles, selectedUserId]
  );

  useEffect(() => {
    if (!selectedUserId) return;
    if (!selectedProfile) {
      setProfileForm(emptyProfileForm());
      return;
    }
    setProfileForm({
      holder_name: selectedProfile.holder_name || "",
      document_type: selectedProfile.document_type || "cpf",
      document_number: selectedProfile.document_number || "",
      payout_method: selectedProfile.payout_method || "pix",
      pix_key_type: selectedProfile.pix_key_type || "cpf",
      pix_key: selectedProfile.pix_key || "",
      bank_name: selectedProfile.bank_name || "",
      bank_code: selectedProfile.bank_code || "",
      agency_number: selectedProfile.agency_number || "",
      agency_digit: selectedProfile.agency_digit || "",
      account_number: selectedProfile.account_number || "",
      account_digit: selectedProfile.account_digit || "",
      account_type: selectedProfile.account_type || "checking",
      notes: selectedProfile.notes || "",
      active: selectedProfile.active !== false,
    });
  }, [selectedProfile, selectedUserId]);

  const stats = useMemo(() => {
    const calculated = events.filter((event) => event.status === "calculated");
    const pending = events.filter((event) => event.status === "pending_source");
    const blocked = events.filter((event) => event.status === "blocked");
    return {
      calculatedAmount: calculated.reduce((sum, event) => sum + Number(event.commission_amount || 0), 0),
      calculatedCount: calculated.length,
      pendingCount: pending.length,
      blockedCount: blocked.length,
    };
  }, [events]);
  const selectedPeriod = useMemo(
    () => periods.find((period) => period.id === selectedPeriodId) || null,
    [periods, selectedPeriodId]
  );
  const periodPayouts = useMemo(
    () => payouts.filter((payout) => (selectedPeriodId ? payout.period_id === selectedPeriodId : true)),
    [payouts, selectedPeriodId]
  );
  const filteredEvents = useMemo(
    () =>
      events.filter((event) => {
        if (selectedUserId && event.seller_user_id !== selectedUserId) return false;
        if (selectedEventStatus && event.status !== selectedEventStatus) return false;
        return true;
      }),
    [events, selectedEventStatus, selectedUserId]
  );
  const filteredAuditLogs = useMemo(
    () =>
      auditLogs.filter((log) => {
        if (selectedAuditEntityType && log.entity_type !== selectedAuditEntityType) return false;
        return true;
      }),
    [auditLogs, selectedAuditEntityType]
  );
  const selectedUserLabel = useMemo(
    () => profileData.users.find((userOption) => userOption.user_id === selectedUserId)?.email || "Nenhuma pessoa selecionada",
    [profileData.users, selectedUserId]
  );
  const nextStep = useMemo(() => {
    if (!plans.length) {
      return {
        title: "Comece criando a regra de comissão",
        description: "Cadastre o primeiro plano para dizer quem recebe comissão e qual percentual será usado.",
        tab: "configuracoes",
        actionLabel: "Abrir configurações",
      };
    }

    if (!profileData.profiles.length) {
      return {
        title: "Preencha os dados de pagamento",
        description: "Antes de gerar pagamentos, informe Pix ou conta bancária da pessoa que vai receber.",
        tab: "configuracoes",
        actionLabel: "Configurar pagamento",
      };
    }

    if (!periods.length) {
      return {
        title: "Feche o primeiro período",
        description: "Depois que já houver vendas com comissão, feche o período para preparar o pagamento.",
        tab: "fechamento",
        actionLabel: "Ir para fechamento",
      };
    }

    if (selectedPeriod && ["closed", "reopened"].includes(selectedPeriod.status)) {
      return {
        title: "Aprove o período selecionado",
        description: "O próximo passo é aprovar este período para liberar a geração dos pagamentos.",
        tab: "fechamento",
        actionLabel: "Revisar período",
      };
    }

    if (selectedPeriod && selectedPeriod.status === "approved" && !periodPayouts.length) {
      return {
        title: "Gere os pagamentos da comissão",
        description: "Com o período aprovado, agora você já pode criar os lançamentos financeiros de comissão.",
        tab: "fechamento",
        actionLabel: "Gerar pagamentos",
      };
    }

    return {
      title: "Acompanhe e revise",
      description: "Seu fluxo principal está configurado. Agora acompanhe eventos, extratos e pagamentos.",
      tab: "pagamentos",
      actionLabel: "Abrir acompanhamento",
    };
  }, [periodPayouts.length, periods.length, plans.length, profileData.profiles.length, selectedPeriod]);

  async function handleCreatePlan(e: React.FormEvent) {
    e.preventDefault();
    try {
      setSavingPlan(true);
      setPlanMessage("");
      const payload = {
        ...planForm,
        percent_value: Number(planForm.percent_value.replace(",", ".")),
      };
      const result = await fetchJson<{ message?: string }>("/api/commissions/plans", {
        method: "POST",
        body: JSON.stringify(payload),
      });
      setPlanMessage(result.message || "Plano criado com sucesso.");
      setPlanForm((prev) => ({
        ...prev,
        name: "",
        description: "",
        percent_value: "5,00",
      }));
      await loadAll();
    } catch (err) {
      setPlanMessage(err instanceof Error ? err.message : "Falha ao criar plano.");
    } finally {
      setSavingPlan(false);
    }
  }

  async function handleSaveProfile(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedUserId) return;
    try {
      setSavingProfile(true);
      setProfileMessage("");
      const result = await fetchJson<{ message?: string }>("/api/commissions/payout-profiles", {
        method: "PUT",
        body: JSON.stringify({
          user_id: selectedUserId,
          ...profileForm,
        }),
      });
      setProfileMessage(result.message || "Perfil salvo com sucesso.");
      await loadAll();
    } catch (err) {
      setProfileMessage(err instanceof Error ? err.message : "Falha ao salvar perfil.");
    } finally {
      setSavingProfile(false);
    }
  }

  async function handlePeriodAction(action: "close" | "approve" | "generate_payouts" | "reopen") {
    try {
      setSavingPeriodAction(true);
      setPeriodMessage("");
      const payload =
        action === "close"
          ? {
              action,
              start_date: periodForm.start_date,
              end_date: periodForm.end_date,
              period_label: periodForm.period_label,
            }
          : action === "reopen"
            ? {
                action,
                period_id: selectedPeriodId,
                reason: periodForm.reopen_reason,
              }
          : {
              action,
              period_id: selectedPeriodId,
              due_date: periodForm.due_date,
            };
      const result = await fetchJson<{ result?: { period_id?: string } }>("/api/commissions/periods", {
        method: "POST",
        body: JSON.stringify(payload),
      });
      setPeriodMessage(
        action === "close"
          ? "Período fechado com sucesso."
          : action === "approve"
            ? "Período aprovado com sucesso."
            : action === "reopen"
              ? "Período reaberto com sucesso."
            : "Payouts e contas a pagar gerados com sucesso."
      );
      if (action === "close" && result.result?.period_id) {
        setSelectedPeriodId(result.result.period_id);
      }
      if (action === "reopen") {
        setPeriodForm((prev) => ({ ...prev, reopen_reason: "" }));
      }
      await loadAll();
    } catch (err) {
      setPeriodMessage(err instanceof Error ? err.message : "Falha na operação do período.");
    } finally {
      setSavingPeriodAction(false);
    }
  }

  async function handleCreateAdjustment(e: React.FormEvent) {
    e.preventDefault();
    try {
      setSavingAdjustment(true);
      setAdjustmentMessage("");
      const result = await fetchJson<{ message?: string }>("/api/commissions/adjustments", {
        method: "POST",
        body: JSON.stringify({
          event_id: adjustmentForm.event_id,
          amount: Number(adjustmentForm.amount.replace(",", ".")),
          reason: adjustmentForm.reason,
        }),
      });
      setAdjustmentMessage(result.message || "Ajuste registrado com sucesso.");
      setAdjustmentForm({ event_id: "", amount: "", reason: "" });
      await loadAll();
    } catch (err) {
      setAdjustmentMessage(err instanceof Error ? err.message : "Falha ao registrar ajuste.");
    } finally {
      setSavingAdjustment(false);
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Financeiro"
        title="Comissões"
        subtitle="Tudo organizado em etapas simples para você saber exatamente o que fazer agora."
        actions={
          <div className="flex flex-wrap items-center gap-2">
            {showMyViewShortcut ? (
              <Button
                variant="outline"
                onClick={() => router.push("/dashboard/my-commissions")}
                icon={<CircleDollarSign size={16} />}
              >
                Minha visão
              </Button>
            ) : null}
            <Button variant="outline" onClick={loadAll} disabled={loading}>
              Atualizar dados
            </Button>
          </div>
        }
      />

      {error ? (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
      ) : null}

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-[1.45fr_1fr]">
        <section className="ks-surface rounded-2xl p-6">
          <div className="inline-flex items-center gap-2 rounded-full bg-[rgba(123,97,255,0.08)] px-3 py-1 text-xs font-semibold text-[var(--ks-color-primary)]">
            <Sparkles size={14} />
            Próximo passo
          </div>
          <h2 className="mt-4 text-2xl font-semibold text-[var(--ks-color-text-primary)]">{nextStep.title}</h2>
          <p className="mt-2 max-w-2xl text-sm text-[var(--ks-color-text-muted)]">{nextStep.description}</p>
          <div className="mt-4 flex flex-wrap items-center gap-3">
            <Button type="button" onClick={() => setActiveTab(nextStep.tab)}>
              {nextStep.actionLabel}
            </Button>
            <div className="inline-flex items-center gap-2 text-sm text-[var(--ks-color-text-muted)]">
              <ArrowRight size={15} />
              Ordem recomendada: configurar, fechar, aprovar, gerar pagamentos e acompanhar
            </div>
          </div>
        </section>

        <section className="ks-surface rounded-2xl p-6">
          <h2 className="text-lg font-semibold text-[var(--ks-color-text-primary)]">Resumo do momento</h2>
          <div className="mt-4 grid gap-3">
            <div className="rounded-2xl border border-slate-200 bg-white p-4">
              <div className="mb-1 flex items-center gap-2 text-sm font-medium text-[var(--ks-color-text-muted)]">
                <Wallet size={16} />
                Comissões prontas
              </div>
              <div className="text-2xl font-bold text-[var(--ks-color-text-primary)]">{formatCurrency(stats.calculatedAmount)}</div>
              <div className="text-xs text-[var(--ks-color-text-muted)]">{stats.calculatedCount} lançamentos prontos para fechamento</div>
            </div>
            <div className="rounded-2xl border border-amber-200 bg-amber-50/70 p-4">
              <div className="mb-1 flex items-center gap-2 text-sm font-medium text-amber-800">
                <Clock3 size={16} />
                Falta configurar
              </div>
              <div className="text-2xl font-bold text-amber-900">{stats.pendingCount}</div>
              <div className="text-xs text-amber-700">Vendas sem plano aplicável</div>
            </div>
            <div className="rounded-2xl border border-rose-200 bg-rose-50/70 p-4">
              <div className="mb-1 flex items-center gap-2 text-sm font-medium text-rose-800">
                <AlertCircle size={16} />
                Precisa revisar
              </div>
              <div className="text-2xl font-bold text-rose-900">{stats.blockedCount}</div>
              <div className="text-xs text-rose-700">Lançamentos bloqueados ou inconsistentes</div>
            </div>
          </div>
        </section>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList className="h-auto w-full flex-wrap justify-start gap-2 rounded-2xl bg-transparent p-0">
          {[
            { value: "comecar", label: "Começar" },
            { value: "configuracoes", label: "Configurações" },
            { value: "fechamento", label: "Fechar e pagar" },
            { value: "pagamentos", label: "Extratos e pagamentos" },
            { value: "historico", label: "Eventos e histórico" },
          ].map((tab) => (
            <TabsTrigger
              key={tab.value}
              value={tab.value}
              className="rounded-xl border border-slate-200 bg-white px-4 py-2.5 data-[state=active]:border-[var(--ks-color-primary)] data-[state=active]:text-[var(--ks-color-primary)]"
            >
              {tab.label}
            </TabsTrigger>
          ))}
        </TabsList>

        <TabsContent value="comecar" className="space-y-6">
          <section className="ks-surface rounded-2xl p-6">
            <div className="mb-5">
              <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Passo a passo</h2>
              <p className="text-sm text-[var(--ks-color-text-muted)]">
                Esta área foi dividida em etapas para facilitar a operação e evitar dúvida sobre o próximo passo.
              </p>
            </div>
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-4">
              {[
                { icon: Settings2, title: "1. Configurar", text: "Cadastre a regra e os dados de pagamento.", tab: "configuracoes" },
                { icon: ListChecks, title: "2. Fechar período", text: "Separe o que entrou naquele intervalo.", tab: "fechamento" },
                { icon: Landmark, title: "3. Gerar pagamentos", text: "Crie os lançamentos financeiros da comissão.", tab: "fechamento" },
                { icon: History, title: "4. Acompanhar", text: "Veja extratos, pagamentos, eventos e auditoria.", tab: "historico" },
              ].map((item) => (
                <button
                  key={item.title}
                  type="button"
                  onClick={() => setActiveTab(item.tab)}
                  className="rounded-2xl border border-slate-200 bg-white p-5 text-left transition hover:border-[var(--ks-color-primary)]/40 hover:shadow-sm"
                >
                  <div className="mb-3 inline-flex rounded-xl bg-[rgba(123,97,255,0.08)] p-3 text-[var(--ks-color-primary)]">
                    <item.icon size={18} />
                  </div>
                  <h3 className="font-semibold text-[var(--ks-color-text-primary)]">{item.title}</h3>
                  <p className="mt-2 text-sm text-[var(--ks-color-text-muted)]">{item.text}</p>
                </button>
              ))}
            </div>
          </section>
        </TabsContent>

        <TabsContent value="configuracoes" className="space-y-6">
          <div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <section className="ks-surface rounded-2xl p-6">
              <div className="mb-4">
                <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Regra da comissão</h2>
                <p className="text-sm text-[var(--ks-color-text-muted)]">
                  Defina aqui quem recebe, quando começa a valer e qual percentual será usado.
                </p>
              </div>
              <form className="space-y-4" onSubmit={handleCreatePlan}>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Nome da regra</label>
                    <input value={planForm.name} onChange={(e) => setPlanForm((prev) => ({ ...prev, name: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Ex: Comissão da equipe de vendas" />
                  </div>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Começa a valer em</label>
                    <input type="date" value={planForm.effective_from} onChange={(e) => setPlanForm((prev) => ({ ...prev, effective_from: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                  </div>
                </div>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Percentual</label>
                    <div className="relative">
                      <input value={planForm.percent_value} onChange={(e) => setPlanForm((prev) => ({ ...prev, percent_value: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 pr-10" placeholder="5,00" />
                      <Percent size={16} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400" />
                    </div>
                  </div>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Vale para quem?</label>
                    <select value={planForm.target_type} onChange={(e) => setPlanForm((prev) => ({ ...prev, target_type: e.target.value as PlanFormState["target_type"] }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="company_default">Toda a empresa</option>
                      <option value="role">Um cargo</option>
                      <option value="user">Uma pessoa específica</option>
                    </select>
                  </div>
                </div>
                {planForm.target_type === "role" ? (
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Cargo</label>
                    <select value={planForm.target_role} onChange={(e) => setPlanForm((prev) => ({ ...prev, target_role: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      {ROLE_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
                    </select>
                  </div>
                ) : null}
                {planForm.target_type === "user" ? (
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Pessoa</label>
                    <select value={planForm.target_user_id} onChange={(e) => setPlanForm((prev) => ({ ...prev, target_user_id: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="">Selecione</option>
                      {profileData.users.map((userOption) => <option key={userOption.user_id} value={userOption.user_id}>{userOption.email} - {userOption.role}</option>)}
                    </select>
                  </div>
                ) : null}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Observações</label>
                  <textarea value={planForm.description} onChange={(e) => setPlanForm((prev) => ({ ...prev, description: e.target.value }))} className="min-h-[84px] w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Explique quando essa regra deve ser usada" />
                </div>
                {planMessage ? <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">{planMessage}</div> : null}
                <Button type="submit" disabled={savingPlan}>{savingPlan ? "Salvando..." : "Salvar regra"}</Button>
              </form>
            </section>

            <section className="ks-surface rounded-2xl p-6">
              <div className="mb-4">
                <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Dados para pagamento</h2>
                <p className="text-sm text-[var(--ks-color-text-muted)]">Informe Pix ou conta bancária da pessoa que vai receber a comissão.</p>
              </div>
              <form className="space-y-4" onSubmit={handleSaveProfile}>
                <div className="space-y-1">
                  <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Pessoa</label>
                  <select value={selectedUserId} onChange={(e) => setSelectedUserId(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                    <option value="">Selecione</option>
                    {profileData.users.map((userOption) => <option key={userOption.user_id} value={userOption.user_id}>{userOption.email} - {userOption.role}</option>)}
                  </select>
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">
                  Pessoa selecionada: <span className="font-medium text-[var(--ks-color-text-primary)]">{selectedUserLabel}</span>
                </div>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Nome do favorecido</label>
                    <input value={profileForm.holder_name} onChange={(e) => setProfileForm((prev) => ({ ...prev, holder_name: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                  </div>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Forma de pagamento</label>
                    <select value={profileForm.payout_method} onChange={(e) => setProfileForm((prev) => ({ ...prev, payout_method: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="pix">Pix</option>
                      <option value="bank_transfer">Transferência bancária</option>
                    </select>
                  </div>
                </div>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Tipo de documento</label>
                    <select value={profileForm.document_type} onChange={(e) => setProfileForm((prev) => ({ ...prev, document_type: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="cpf">CPF</option>
                      <option value="cnpj">CNPJ</option>
                    </select>
                  </div>
                  <div className="space-y-1 md:col-span-2">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Número do documento</label>
                    <input value={profileForm.document_number} onChange={(e) => setProfileForm((prev) => ({ ...prev, document_number: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                  </div>
                </div>
                {profileForm.payout_method === "pix" ? (
                  <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <div className="space-y-1">
                      <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Tipo da chave Pix</label>
                      <select value={profileForm.pix_key_type} onChange={(e) => setProfileForm((prev) => ({ ...prev, pix_key_type: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                        <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="space-y-1">
                      <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Chave Pix</label>
                      <input value={profileForm.pix_key} onChange={(e) => setProfileForm((prev) => ({ ...prev, pix_key: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                      <div className="space-y-1">
                        <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Banco</label>
                        <input value={profileForm.bank_name} onChange={(e) => setProfileForm((prev) => ({ ...prev, bank_name: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                      </div>
                      <div className="space-y-1">
                        <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Código do banco</label>
                        <input value={profileForm.bank_code} onChange={(e) => setProfileForm((prev) => ({ ...prev, bank_code: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
                      <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Agência</label><input value={profileForm.agency_number} onChange={(e) => setProfileForm((prev) => ({ ...prev, agency_number: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                      <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Dígito da agência</label><input value={profileForm.agency_digit} onChange={(e) => setProfileForm((prev) => ({ ...prev, agency_digit: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                      <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Conta</label><input value={profileForm.account_number} onChange={(e) => setProfileForm((prev) => ({ ...prev, account_number: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                      <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Dígito da conta</label><input value={profileForm.account_digit} onChange={(e) => setProfileForm((prev) => ({ ...prev, account_digit: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                    </div>
                  </>
                )}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Observações</label>
                  <textarea value={profileForm.notes} onChange={(e) => setProfileForm((prev) => ({ ...prev, notes: e.target.value }))} className="min-h-[84px] w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Ex: sempre pagar por Pix" />
                </div>
                {profileMessage ? <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">{profileMessage}</div> : null}
                <Button type="submit" disabled={!selectedUserId || savingProfile}>{savingProfile ? "Salvando..." : "Salvar dados de pagamento"}</Button>
              </form>
            </section>
          </div>

          <section className="ks-surface rounded-2xl p-6">
            <div className="mb-4">
              <h2 className="text-lg font-semibold text-[var(--ks-color-text-primary)]">Regras já cadastradas</h2>
              <p className="text-sm text-[var(--ks-color-text-muted)]">Antes de operar, confira se as regras já estão do jeito que você precisa.</p>
            </div>
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
              {plans.map((plan) => {
                const latestVersion = plan.versions[0];
                const defaultRule = latestVersion?.rules?.[0];
                const defaultAssignment = latestVersion?.assignments?.[0];
                return (
                  <div key={plan.id} className="rounded-2xl border border-slate-200 bg-white p-5">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <h3 className="font-semibold text-[var(--ks-color-text-primary)]">{plan.name}</h3>
                        <p className="text-sm text-[var(--ks-color-text-muted)]">{plan.description || "Sem observações"}</p>
                      </div>
                      <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getStatusTone(plan.status)}`}>{translateStatus(plan.status)}</span>
                    </div>
                    <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
                      <div><div className="text-[var(--ks-color-text-muted)]">Versão atual</div><div className="font-medium text-[var(--ks-color-text-primary)]">{latestVersion ? `${latestVersion.version_number} - ${translateStatus(latestVersion.status)}` : "Sem versão"}</div></div>
                      <div><div className="text-[var(--ks-color-text-muted)]">Começa em</div><div className="font-medium text-[var(--ks-color-text-primary)]">{latestVersion ? formatDate(latestVersion.effective_from) : "-"}</div></div>
                      <div><div className="text-[var(--ks-color-text-muted)]">Percentual padrão</div><div className="font-medium text-[var(--ks-color-text-primary)]">{defaultRule?.percent_value ? `${defaultRule.percent_value}%` : "Sem percentual"}</div></div>
                      <div><div className="text-[var(--ks-color-text-muted)]">Aplica para</div><div className="font-medium text-[var(--ks-color-text-primary)]">{translateTarget(defaultAssignment)}</div></div>
                    </div>
                  </div>
                );
              })}
              {!plans.length && !loading ? <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-sm text-slate-600">Você ainda não cadastrou nenhuma regra de comissão.</div> : null}
            </div>
          </section>
        </TabsContent>

        <TabsContent value="fechamento" className="space-y-6">
          <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.2fr_1fr]">
            <section className="ks-surface rounded-2xl p-6">
              <div className="mb-4">
                <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Fechar, aprovar e gerar pagamentos</h2>
                <p className="text-sm text-[var(--ks-color-text-muted)]">Siga esta ordem para evitar erro: fechar, aprovar e só depois gerar os pagamentos.</p>
              </div>
              <div className="mb-5 grid grid-cols-1 gap-3 md:grid-cols-3">
                {["1. Fechar", "2. Aprovar", "3. Gerar pagamentos"].map((item) => <div key={item} className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm font-medium text-[var(--ks-color-text-primary)]">{item}</div>)}
              </div>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Data inicial</label><input type="date" value={periodForm.start_date} onChange={(e) => setPeriodForm((prev) => ({ ...prev, start_date: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Data final</label><input type="date" value={periodForm.end_date} onChange={(e) => setPeriodForm((prev) => ({ ...prev, end_date: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
                <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Nome do período</label><input value={periodForm.period_label} onChange={(e) => setPeriodForm((prev) => ({ ...prev, period_label: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Ex: Abril/2026" /></div>
                <div className="space-y-1"><label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Data de vencimento do pagamento</label><input type="date" value={periodForm.due_date} onChange={(e) => setPeriodForm((prev) => ({ ...prev, due_date: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" /></div>
              </div>
              <div className="mt-5 flex flex-wrap gap-3">
                <Button type="button" disabled={savingPeriodAction} onClick={() => handlePeriodAction("close")}>{savingPeriodAction ? "Processando..." : "Fechar período"}</Button>
                <Button type="button" variant="outline" disabled={!selectedPeriodId || savingPeriodAction} onClick={() => handlePeriodAction("approve")}>Aprovar período</Button>
                <Button type="button" variant="outline" disabled={!selectedPeriodId || savingPeriodAction} onClick={() => handlePeriodAction("generate_payouts")}>Gerar pagamentos</Button>
              </div>
              <div className="mt-6 rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="mb-2 flex items-center gap-2 text-sm font-semibold text-[var(--ks-color-text-primary)]"><ShieldCheck size={16} /> Reabrir período</div>
                <p className="mb-3 text-sm text-[var(--ks-color-text-muted)]">Use isso apenas quando realmente precisar corrigir um fechamento. Se já existir pagamento ativo, o sistema bloqueia.</p>
                <textarea value={periodForm.reopen_reason} onChange={(e) => setPeriodForm((prev) => ({ ...prev, reopen_reason: e.target.value }))} className="min-h-[84px] w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Explique o motivo da reabertura" />
                <div className="mt-3"><Button type="button" variant="outline" disabled={!selectedPeriodId || savingPeriodAction || !periodForm.reopen_reason.trim()} onClick={() => handlePeriodAction("reopen")}>Reabrir período</Button></div>
              </div>
              {periodMessage ? <div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">{periodMessage}</div> : null}
            </section>

            <section className="ks-surface rounded-2xl p-6">
              <div className="mb-4">
                <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Períodos criados</h2>
                <p className="text-sm text-[var(--ks-color-text-muted)]">Escolha o período que você quer revisar, aprovar ou pagar.</p>
              </div>
              <div className="space-y-3">
                {periods.map((period) => (
                  <button key={period.id} type="button" onClick={() => setSelectedPeriodId(period.id)} className={`w-full rounded-2xl border px-4 py-4 text-left transition ${selectedPeriodId === period.id ? "border-[var(--ks-color-primary)] bg-[rgba(123,97,255,0.06)]" : "border-slate-200 bg-white"}`}>
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="font-semibold text-[var(--ks-color-text-primary)]">{period.period_label}</div>
                        <div className="text-sm text-[var(--ks-color-text-muted)]">{formatDate(period.start_date)} até {formatDate(period.end_date)}</div>
                      </div>
                      <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getStatusTone(period.status)}`}>{translateStatus(period.status)}</span>
                    </div>
                  </button>
                ))}
                {!periods.length && !loading ? <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-sm text-slate-600">Você ainda não fechou nenhum período.</div> : null}
              </div>
            </section>
          </div>
        </TabsContent>

        <TabsContent value="pagamentos" className="space-y-6">
          <section className="ks-surface rounded-2xl p-6">
            <div className="mb-4 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
              <div>
                <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Extratos e pagamentos</h2>
                <p className="text-sm text-[var(--ks-color-text-muted)]">Escolha a pessoa e o período para enxergar exatamente o que entrou e o que já foi para pagamento.</p>
              </div>
              <div className="grid w-full gap-3 sm:grid-cols-2 lg:w-[520px]">
                <select value={selectedUserId} onChange={(e) => setSelectedUserId(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                  <option value="">Todas as pessoas</option>
                  {profileData.users.map((userOption) => <option key={userOption.user_id} value={userOption.user_id}>{userOption.email} - {userOption.role}</option>)}
                </select>
                <select value={selectedPeriodId} onChange={(e) => setSelectedPeriodId(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                  <option value="">Todos os períodos</option>
                  {periods.map((period) => <option key={period.id} value={period.id}>{period.period_label}</option>)}
                </select>
              </div>
            </div>
            <div className="mb-5 grid grid-cols-1 gap-4 md:grid-cols-3">
              <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4"><div className="text-xs text-[var(--ks-color-text-muted)]">Pessoa selecionada</div><div className="mt-1 font-medium text-[var(--ks-color-text-primary)]">{selectedUserLabel}</div></div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4"><div className="text-xs text-[var(--ks-color-text-muted)]">Total no extrato</div><div className="mt-1 font-medium text-[var(--ks-color-text-primary)]">{formatCurrency(statementData.summary.total_amount)}</div></div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4"><div className="text-xs text-[var(--ks-color-text-muted)]">Já incluído em pagamento</div><div className="mt-1 font-medium text-[var(--ks-color-text-primary)]">{formatCurrency(statementData.summary.payout_eligible_amount)}</div></div>
            </div>
            <div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
              <div className="rounded-2xl border border-slate-200 bg-white p-5">
                <div className="mb-4"><h3 className="font-semibold text-[var(--ks-color-text-primary)]">Itens do extrato</h3><p className="text-sm text-[var(--ks-color-text-muted)]">O que entrou no período e se já foi levado para pagamento.</p></div>
                <div className="overflow-x-auto">
                  <table className="min-w-full text-sm">
                    <thead><tr className="border-b border-slate-200 text-left text-[var(--ks-color-text-muted)]"><th className="px-3 py-2">Período</th><th className="px-3 py-2">Tipo</th><th className="px-3 py-2">Valor</th><th className="px-3 py-2">Já foi para pagamento?</th></tr></thead>
                    <tbody>
                      {statementData.items.map((item) => <tr key={item.id} className="border-b border-slate-100"><td className="px-3 py-2">{item.period?.period_label || "-"}</td><td className="px-3 py-2">{translateStatementType(item.statement_type)}</td><td className="px-3 py-2 font-medium text-[var(--ks-color-text-primary)]">{formatCurrency(item.amount)}</td><td className="px-3 py-2">{item.included_in_payout ? "Sim" : "Ainda não"}</td></tr>)}
                      {!statementData.items.length && !loading ? <tr><td colSpan={4} className="px-3 py-6 text-center text-sm text-slate-500">Nenhum item encontrado para os filtros escolhidos.</td></tr> : null}
                    </tbody>
                  </table>
                </div>
              </div>
              <div className="rounded-2xl border border-slate-200 bg-white p-5">
                <div className="mb-4"><h3 className="font-semibold text-[var(--ks-color-text-primary)]">Pagamentos gerados</h3><p className="text-sm text-[var(--ks-color-text-muted)]">O que já virou lançamento financeiro da comissão.</p></div>
                <div className="overflow-x-auto">
                  <table className="min-w-full text-sm">
                    <thead><tr className="border-b border-slate-200 text-left text-[var(--ks-color-text-muted)]"><th className="px-3 py-2">Pessoa</th><th className="px-3 py-2">Período</th><th className="px-3 py-2">Valor</th><th className="px-3 py-2">Situação</th></tr></thead>
                    <tbody>
                      {periodPayouts.map((payout) => (
                        <tr key={payout.id} className="border-b border-slate-100">
                          <td className="px-3 py-2"><div className="font-medium text-[var(--ks-color-text-primary)]">{payout.seller_email || payout.seller_user_id}</div><div className="text-xs text-[var(--ks-color-text-muted)]">{payout.seller_role || "-"}</div></td>
                          <td className="px-3 py-2">{payout.period?.period_label || "-"}</td>
                          <td className="px-3 py-2 font-medium text-[var(--ks-color-text-primary)]">{formatCurrency(payout.net_amount)}</td>
                          <td className="px-3 py-2"><span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getStatusTone(payout.status)}`}>{translateStatus(payout.status)}</span></td>
                        </tr>
                      ))}
                      {!periodPayouts.length && !loading ? <tr><td colSpan={4} className="px-3 py-6 text-center text-sm text-slate-500">Nenhum pagamento gerado para os filtros escolhidos.</td></tr> : null}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </section>
        </TabsContent>

        <TabsContent value="historico" className="space-y-6">
          <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.15fr_0.85fr]">
            <section className="ks-surface rounded-2xl p-6">
              <div className="mb-4 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                <div>
                  <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Eventos da comissão</h2>
                  <p className="text-sm text-[var(--ks-color-text-muted)]">Aqui aparecem os lançamentos gerados pelo sistema e o que precisa de revisão.</p>
                </div>
                <div className="grid w-full gap-3 sm:grid-cols-2 lg:w-[420px]">
                  <select value={selectedUserId} onChange={(e) => setSelectedUserId(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                    <option value="">Todas as pessoas</option>
                    {profileData.users.map((userOption) => <option key={userOption.user_id} value={userOption.user_id}>{userOption.email} - {userOption.role}</option>)}
                  </select>
                  <select value={selectedEventStatus} onChange={(e) => setSelectedEventStatus(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                    <option value="">Todas as situações</option>
                    <option value="calculated">Pronto para fechar</option>
                    <option value="pending_source">Falta configurar</option>
                    <option value="blocked">Precisa revisar</option>
                    <option value="reversed">Estornado</option>
                    <option value="closed">Fechado</option>
                    <option value="paid">Pago</option>
                  </select>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="min-w-full text-sm">
                  <thead><tr className="border-b border-slate-200 text-left text-[var(--ks-color-text-muted)]"><th className="px-3 py-2">Data</th><th className="px-3 py-2">Pessoa</th><th className="px-3 py-2">Pedido</th><th className="px-3 py-2">Base</th><th className="px-3 py-2">Comissão</th><th className="px-3 py-2">Situação</th></tr></thead>
                  <tbody>
                    {filteredEvents.map((event) => (
                      <tr key={event.id} className="border-b border-slate-100">
                        <td className="px-3 py-2">{formatDate(event.source_date)}</td>
                        <td className="px-3 py-2"><div className="font-medium text-[var(--ks-color-text-primary)]">{event.seller_email || event.seller_user_id}</div><div className="text-xs text-[var(--ks-color-text-muted)]">{event.seller_role || "-"}</div></td>
                        <td className="px-3 py-2">{event.order_number ? `#${event.order_number}` : "-"}</td>
                        <td className="px-3 py-2">{formatCurrency(event.gross_basis_amount)}</td>
                        <td className="px-3 py-2 font-medium text-[var(--ks-color-text-primary)]">{formatCurrency(event.commission_amount)}<div className="text-xs text-[var(--ks-color-text-muted)]">{event.commission_percent ? `${event.commission_percent}%` : "Sem percentual"}</div></td>
                        <td className="px-3 py-2"><span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getStatusTone(event.status)}`}>{translateStatus(event.status)}</span>{event.notes ? <div className="mt-1 text-xs text-[var(--ks-color-text-muted)]">{event.notes}</div> : null}</td>
                      </tr>
                    ))}
                    {!filteredEvents.length && !loading ? <tr><td colSpan={6} className="px-3 py-6 text-center text-sm text-slate-500">Nenhum evento encontrado para os filtros escolhidos.</td></tr> : null}
                  </tbody>
                </table>
              </div>
            </section>

            <div className="space-y-6">
              <section className="ks-surface rounded-2xl p-6">
                <div className="mb-4">
                  <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Ajuste manual</h2>
                  <p className="text-sm text-[var(--ks-color-text-muted)]">Use apenas para corrigir uma exceção real. O motivo fica salvo no histórico.</p>
                </div>
                <form className="space-y-4" onSubmit={handleCreateAdjustment}>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Lançamento que será ajustado</label>
                    <select value={adjustmentForm.event_id} onChange={(e) => setAdjustmentForm((prev) => ({ ...prev, event_id: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="">Selecione</option>
                      {filteredEvents.map((event) => <option key={event.id} value={event.id}>{`${formatDate(event.source_date)} - ${event.seller_email || event.seller_user_id} - ${formatCurrency(event.commission_amount)}`}</option>)}
                    </select>
                  </div>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Valor do ajuste</label>
                    <input value={adjustmentForm.amount} onChange={(e) => setAdjustmentForm((prev) => ({ ...prev, amount: e.target.value }))} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Ex: 15,00 ou -15,00" />
                  </div>
                  <div className="space-y-1">
                    <label className="text-sm font-medium text-[var(--ks-color-text-primary)]">Motivo</label>
                    <textarea value={adjustmentForm.reason} onChange={(e) => setAdjustmentForm((prev) => ({ ...prev, reason: e.target.value }))} className="min-h-[92px] w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5" placeholder="Explique o motivo do ajuste" />
                  </div>
                  {adjustmentMessage ? <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">{adjustmentMessage}</div> : null}
                  <Button type="submit" disabled={savingAdjustment}>{savingAdjustment ? "Registrando..." : "Registrar ajuste"}</Button>
                </form>
              </section>

              <section className="ks-surface rounded-2xl p-6">
                <div className="mb-4 flex items-start justify-between gap-4">
                  <div>
                    <h2 className="text-xl font-semibold text-[var(--ks-color-text-primary)]">Histórico</h2>
                    <p className="text-sm text-[var(--ks-color-text-muted)]">Acompanhe as ações importantes do processo.</p>
                  </div>
                  <div className="w-full max-w-[220px]">
                    <select value={selectedAuditEntityType} onChange={(e) => setSelectedAuditEntityType(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                      <option value="">Tudo</option>
                      <option value="commission_event">Eventos</option>
                      <option value="commission_period">Períodos</option>
                      <option value="commission_payout">Pagamentos</option>
                    </select>
                  </div>
                </div>
                <div className="space-y-3">
                  {filteredAuditLogs.map((log) => (
                    <div key={log.id} className="rounded-2xl border border-slate-200 bg-white p-4">
                      <div className="flex items-start justify-between gap-3">
                        <div>
                          <div className="font-medium text-[var(--ks-color-text-primary)]">{translateAuditAction(log.action)}</div>
                          <div className="text-sm text-[var(--ks-color-text-muted)]">
                            {log.actor_email || "Sistema"} {log.actor_role ? `• ${translateRole(log.actor_role)}` : ""}
                          </div>
                        </div>
                        <div className="text-xs text-[var(--ks-color-text-muted)]">{formatDate(log.created_at)}</div>
                      </div>
                      <div className="mt-2 text-sm text-[var(--ks-color-text-muted)]">
                        Tipo: {translateAuditEntityType(log.entity_type)}
                        {log.reason ? ` • ${translateAuditReason(log.reason)}` : ""}
                      </div>
                    </div>
                  ))}
                  {!filteredAuditLogs.length && !loading ? <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-sm text-slate-600">Nenhum registro encontrado para esse filtro.</div> : null}
                </div>
              </section>
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
