import { TICKET_CATEGORIES, type TicketCategory } from "@/components/help/helpTicketConstants";
import type { ChatContact } from "@/lib/helpChat";
import { setChatContact } from "@/lib/helpChat";

export const CHAT_INTAKE_STEP_KEY = "noga-help-intake-step";
export const CHAT_INTAKE_DRAFT_KEY = "noga-help-intake-draft";

export type IntakeStepId =
  | "greeting"
  | "is_customer"
  | "name"
  | "email"
  | "phone"
  | "company"
  | "category"
  | "preferred_contact"
  | "confirm"
  | "done";

export type IntakeDraft = {
  isCustomer?: boolean;
  name?: string;
  email?: string;
  phone?: string;
  company?: string;
  ticketCategory?: TicketCategory;
  preferredContact?: "email" | "whatsapp" | "both";
};

export type IntakeChoice = { label: string; value: string };

export type IntakeBotTurn = {
  messages: string[];
  choices?: IntakeChoice[];
  placeholder?: string;
};

export function getIntakeStep(): IntakeStepId {
  if (typeof window === "undefined") return "done";
  const raw = sessionStorage.getItem(CHAT_INTAKE_STEP_KEY);
  if (raw === "done" || !raw) return getChatContactFromStorage() ? "done" : "greeting";
  if (raw === "preferred_contact") return "confirm";
  return raw as IntakeStepId;
}

function getChatContactFromStorage(): ChatContact | null {
  try {
    const raw = sessionStorage.getItem("noga-help-chat-contact");
    if (!raw) return null;
    const p = JSON.parse(raw) as ChatContact;
    return p.name && p.email && p.phone ? p : null;
  } catch {
    return null;
  }
}

export function setIntakeStep(step: IntakeStepId) {
  sessionStorage.setItem(CHAT_INTAKE_STEP_KEY, step);
}

export function getIntakeDraft(): IntakeDraft {
  if (typeof window === "undefined") return {};
  try {
    const raw = sessionStorage.getItem(CHAT_INTAKE_DRAFT_KEY);
    return raw ? (JSON.parse(raw) as IntakeDraft) : {};
  } catch {
    return {};
  }
}

export function setIntakeDraft(draft: IntakeDraft) {
  sessionStorage.setItem(CHAT_INTAKE_DRAFT_KEY, JSON.stringify(draft));
}

export function clearIntakeProgress() {
  sessionStorage.removeItem(CHAT_INTAKE_STEP_KEY);
  sessionStorage.removeItem(CHAT_INTAKE_DRAFT_KEY);
}

export function intakeIsComplete(): boolean {
  return getIntakeStep() === "done" || Boolean(getChatContactFromStorage());
}

/** Primeira mensagem automática ao abrir o chat */
export function startIntakeTurn(draft: IntakeDraft): { step: IntakeStepId; turn: IntakeBotTurn } {
  setIntakeStep("greeting");
  return {
    step: "is_customer",
    turn: {
      messages: [
        `Olá! Sou o assistente virtual da NOGA CODE.`,
        `Para conectar você a um atendente, preciso de algumas informações. Leva só um minuto.`,
        botForStep("is_customer", draft).messages[0],
      ],
      choices: botForStep("is_customer", draft).choices,
      placeholder: "Digite algo...",
    },
  };
}

export function resumeIntakeTurn(step: IntakeStepId, draft: IntakeDraft): IntakeBotTurn {
  if (step === "greeting") return startIntakeTurn(draft).turn;
  if (step === "preferred_contact") {
    setIntakeStep("confirm");
    return botForStep("confirm", draft);
  }
  return botForStep(step, draft);
}

function botForStep(step: IntakeStepId, draft: IntakeDraft): IntakeBotTurn {
  switch (step) {
    case "is_customer":
      return {
        messages: ["Você já é cliente da NOGA CODE?"],
        choices: [
          { label: "Sim, sou cliente", value: "yes" },
          { label: "Ainda não sou cliente", value: "no" },
          { label: "Quero conhecer os serviços", value: "prospect" },
        ],
      };
    case "name":
      return {
        messages: ["Perfeito! Qual é o seu nome completo?"],
        placeholder: "Digite algo...",
      };
    case "email":
      return {
        messages: [`Obrigado, ${firstName(draft.name)}! Qual é o seu melhor e-mail?`],
        placeholder: "Digite algo...",
      };
    case "phone":
      return {
        messages: ["Qual WhatsApp ou telefone podemos usar para retorno? (com DDD)"],
        placeholder: "Digite seu número de telefone",
      };
    case "company":
      return {
        messages: [
          "Qual o nome da sua empresa ou projeto?",
          "Se não se aplicar, digite pular ou -",
        ],
        placeholder: "Digite algo...",
      };
    case "category":
      return {
        messages: ["Sobre qual assunto você precisa de ajuda?"],
        choices: TICKET_CATEGORIES.map((c) => ({ label: c.label, value: c.value })),
        placeholder: "Digite algo...",
      };
    case "preferred_contact":
      return botForStep("confirm", draft);
    case "confirm": {
      const summary = formatSummary(draft);
      return {
        messages: [
          "Confira seus dados:",
          summary,
          "Está tudo certo? Digite sim para falar com o atendente ou não para corrigir o nome.",
        ],
        choices: [
          { label: "Sim, continuar", value: "sim" },
          { label: "Corrigir nome", value: "corrigir" },
        ],
      };
    }
    default:
      return { messages: [] };
  }
}

function firstName(name?: string) {
  return name?.trim().split(/\s+/)[0] || "";
}

function formatSummary(draft: IntakeDraft) {
  const cat = TICKET_CATEGORIES.find((c) => c.value === draft.ticketCategory)?.label ?? "—";
  const lines = [
    `• Cliente NOGA: ${draft.isCustomer ? "Sim" : "Não / em prospecção"}`,
    `• Nome: ${draft.name}`,
    `• E-mail: ${draft.email}`,
    `• Telefone: ${draft.phone}`,
    `• Empresa: ${draft.company || "—"}`,
    `• Assunto: ${cat}`,
    `• Propostas e contratos: painel da conta em /dashboard`,
  ];
  return lines.join("\n");
}

function parseCustomerAnswer(text: string): boolean | null {
  const t = text.trim().toLowerCase();
  if (["sim", "s", "yes", "y", "1", "sou cliente", "yes"].includes(t) || t.includes("sim")) return true;
  if (["não", "nao", "n", "no", "2", "não sou", "nao sou"].includes(t) || t.includes("não") || t.includes("nao"))
    return false;
  if (t.includes("conhecer") || t.includes("prospect")) return false;
  return null;
}

function parseCategory(text: string): TicketCategory | null {
  const t = text.trim().toLowerCase();
  const byNum = /^(\d+)$/.exec(t);
  if (byNum) {
    const idx = Number(byNum[1]) - 1;
    if (TICKET_CATEGORIES[idx]) return TICKET_CATEGORIES[idx].value;
  }
  const found = TICKET_CATEGORIES.find(
    (c) => c.label.toLowerCase().includes(t) || c.value === t,
  );
  return found?.value ?? null;
}

export type IntakeProcessResult =
  | {
      ok: true;
      draft: IntakeDraft;
      nextStep: IntakeStepId;
      botTurn?: IntakeBotTurn;
      contact?: ChatContact;
    }
  | { ok: false; error: string; retry: boolean };

export function processIntakeReply(
  step: IntakeStepId,
  draft: IntakeDraft,
  userText: string,
): IntakeProcessResult {
  const text = userText.trim();
  if (!text) {
    return { ok: false, error: "Por favor, digite uma resposta para continuar.", retry: true };
  }

  const next = { ...draft };

  switch (step) {
    case "is_customer": {
      const v = text.toLowerCase();
      let isCustomer: boolean | null = null;
      if (v === "yes" || v === "sim") isCustomer = true;
      else if (v === "no" || v === "prospect") isCustomer = false;
      else isCustomer = parseCustomerAnswer(text);
      if (isCustomer === null) {
        return {
          ok: false,
          error: "Escolha: Sim, Não ou Quero conhecer — ou digite sua resposta.",
          retry: true,
        };
      }
      next.isCustomer = isCustomer;
      setIntakeDraft(next);
      setIntakeStep("name");
      return { ok: true, draft: next, nextStep: "name", botTurn: botForStep("name", next) };
    }

    case "name": {
      if (text.length < 3) {
        return { ok: false, error: "Informe seu nome completo (mínimo 3 caracteres).", retry: true };
      }
      next.name = text;
      setIntakeDraft(next);
      setIntakeStep("email");
      return { ok: true, draft: next, nextStep: "email", botTurn: botForStep("email", next) };
    }

    case "email": {
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text)) {
        return { ok: false, error: "E-mail inválido. Ex.: nome@empresa.com", retry: true };
      }
      next.email = text;
      setIntakeDraft(next);
      setIntakeStep("phone");
      return { ok: true, draft: next, nextStep: "phone", botTurn: botForStep("phone", next) };
    }

    case "phone": {
      const digits = text.replace(/\D/g, "");
      if (digits.length < 10) {
        return { ok: false, error: "Informe telefone/WhatsApp com DDD (mín. 10 dígitos).", retry: true };
      }
      next.phone = text;
      setIntakeDraft(next);
      setIntakeStep("company");
      return { ok: true, draft: next, nextStep: "company", botTurn: botForStep("company", next) };
    }

    case "company": {
      const skip = ["pular", "-", "na", "n/a", "não tenho", "nao tenho", "particular"].includes(
        text.toLowerCase(),
      );
      next.company = skip ? undefined : text;
      setIntakeDraft(next);
      setIntakeStep("category");
      return { ok: true, draft: next, nextStep: "category", botTurn: botForStep("category", next) };
    }

    case "category": {
      const cat = parseCategory(text);
      if (!cat) {
        return {
          ok: false,
          error: "Escolha um assunto da lista ou digite o número da opção.",
          retry: true,
        };
      }
      next.ticketCategory = cat;
      setIntakeDraft(next);
      setIntakeStep("confirm");
      return { ok: true, draft: next, nextStep: "confirm", botTurn: botForStep("confirm", next) };
    }

    case "preferred_contact":
      setIntakeStep("confirm");
      return { ok: true, draft: next, nextStep: "confirm", botTurn: botForStep("confirm", next) };

    case "confirm": {
      const t = text.toLowerCase();
      if (t === "corrigir" || t.includes("corrigir") || t === "não" || t === "nao") {
        setIntakeStep("name");
        return {
          ok: true,
          draft: next,
          nextStep: "name",
          botTurn: { messages: ["Sem problemas. Qual é o seu nome completo?"], placeholder: "Digite algo..." },
        };
      }
      if (!["sim", "s", "yes", "ok", "confirmar", "continuar"].some((w) => t === w || t.startsWith(w))) {
        return { ok: false, error: 'Digite "sim" para continuar ou "corrigir" para alterar o nome.', retry: true };
      }

      const contact: ChatContact = {
        name: next.name!,
        email: next.email!,
        phone: next.phone!,
        company: next.company,
        ticketCategory: next.ticketCategory ?? "technical",
        preferredContact: next.preferredContact ?? "both",
        isCustomer: next.isCustomer ?? true,
      };

      setChatContact(contact);
      setIntakeStep("done");
      clearIntakeProgress();

      return {
        ok: true,
        draft: next,
        nextStep: "done",
        contact,
        botTurn: {
          messages: [
            `Perfeito, ${firstName(contact.name)}! Seus dados foram registrados.`,
            "Propostas e contratos ficam no painel da sua conta (/dashboard). Aqui no chat, envie sua dúvida — a assistente virtual responde na hora; se precisar, um humano assume depois.",
          ],
          placeholder: "Digite algo...",
        },
      };
    }

    default:
      return { ok: false, error: "Sessão encerrada. Reabra o chat.", retry: false };
  }
}

/** Monta mensagem inicial do ticket com resumo do intake */
export function buildIntakeTicketMessage(draft: IntakeDraft): string {
  return `--- Dados do atendimento (chat) ---\n${formatSummary(draft)}\n---\nCliente aguardando atendimento.`;
}
