import type { Plan, PlanLimitationsMeta } from "@/types/plan";
import { planToPlanningPlanView } from "@/lib/planningPlans";
import { sanitizeCommerceCopy } from "@/lib/sanitizeCommerceCopy";

function inferAppFormatFromPlatforms(platforms: string[]): string {
  const hasPwa = platforms.includes("pwa");
  const hasAndroid = platforms.includes("android");
  const hasIos = platforms.includes("ios");

  if (hasPwa && hasAndroid && hasIos) return "full";
  if (hasAndroid && hasIos) return "android-ios";
  if (hasIos) return "ios";
  if (hasAndroid) return "android";
  if (hasPwa) return "pwa";
  return "android-ios";
}

export interface PlanFeatureDisplay {
  label: string;
  included: boolean;
}

export interface PlanDisplayCard {
  id: number;
  slug: string;
  name: string;
  badge?: string;
  featured: boolean;
  idealFor: string[];
  description: string;
  features: PlanFeatureDisplay[];
  buttonText?: string;
  screenEstimate?: string;
  structuralDescription?: string;
  planningNotice?: string;
}

export type { PlanLimitationsMeta };

const FALLBACK_META: Record<string, PlanLimitationsMeta> = {
  starter: {
    idealFor: ["MVP", "pequenos negócios", "validação rápida"],
    appFormatId: "android",
    defaultModules: ["admin-panel", "push"],
    featureChecklist: [
      { label: "PWA", included: true },
      { label: "Android", included: true },
      { label: "iOS", included: false },
      { label: "Painel Gestão Básico", included: true },
      { label: "Website", included: true },
    ],
  },
  business: {
    idealFor: ["empresas em crescimento", "delivery", "automação"],
    appFormatId: "android-ios",
    defaultModules: ["admin-panel", "payments", "push", "whatsapp"],
    featureChecklist: [
      { label: "PWA", included: true },
      { label: "Android", included: true },
      { label: "iOS", included: true },
      { label: "Painel Gestão", included: true },
      { label: "Website", included: true },
      { label: "Help Desk", included: true },
    ],
  },
  enterprise: {
    idealFor: ["marketplace", "multiempresa", "plataformas escaláveis"],
    appFormatId: "full",
    defaultModules: [
      "admin-panel",
      "multi-company",
      "payments",
      "push",
      "whatsapp",
      "ai",
    ],
    featureChecklist: [
      { label: "PWA", included: true },
      { label: "Android", included: true },
      { label: "iOS", included: true },
      { label: "Painel Enterprise", included: true },
      { label: "Website Premium", included: true },
      { label: "Help Desk Enterprise", included: true },
    ],
  },
};

function withoutHelpDeskForStarter(
  slug: string,
  features: PlanFeatureDisplay[],
): PlanFeatureDisplay[] {
  if (slug !== "starter") return features;
  return features.filter((f) => !/^help desk$/i.test(f.label.trim()));
}

export function getPlanMeta(plan: Plan): PlanLimitationsMeta {
  const fromDb = (plan.limitations ?? {}) as PlanLimitationsMeta;
  const fallback = FALLBACK_META[plan.slug] ?? {};
  return {
    idealFor: fromDb.idealFor ?? fallback.idealFor,
    appFormatId: fromDb.appFormatId ?? fallback.appFormatId,
    defaultModules: fromDb.defaultModules ?? fallback.defaultModules,
    featureChecklist: fromDb.featureChecklist?.length
      ? fromDb.featureChecklist
      : fallback.featureChecklist,
  };
}

export function planToDisplayCard(plan: Plan): PlanDisplayCard {
  const meta = getPlanMeta(plan);
  const planFeatureRows = Array.isArray(plan.planFeatures) ? plan.planFeatures : [];
  const rawFeatures =
    meta.featureChecklist?.length
      ? meta.featureChecklist
      : planFeatureRows.length
        ? planFeatureRows
            .filter((f) => f && typeof f.feature === "string")
            .map((f) => ({
              label: f.feature,
              included: true,
            }))
        : (Array.isArray(plan.features) ? plan.features : []).map((label) => ({
            label: String(label),
            included: true,
          }));
  const features = withoutHelpDeskForStarter(plan.slug, rawFeatures);

  const idealFor =
    meta.idealFor?.length
      ? meta.idealFor
      : plan.shortDescription
        ? [plan.shortDescription]
        : [plan.description].filter(Boolean);

  const lim = (plan.limitations ?? {}) as PlanLimitationsMeta;
  const planningView = planToPlanningPlanView(plan);

  return {
    id: plan.id,
    slug: plan.slug,
    name: plan.name,
    badge: plan.badge ?? undefined,
    featured: plan.featured,
    idealFor,
    description: sanitizeCommerceCopy(plan.shortDescription || plan.description),
    features,
    buttonText: plan.buttonText ?? undefined,
    screenEstimate: lim.screenEstimate ?? planningView.screenEstimate,
    structuralDescription:
      lim.structuralDescription ?? planningView.structuralDescription,
    planningNotice: lim.planningNotice ?? planningView.planningNotice,
  };
}

export function getPlanAppFormatId(
  plan: Plan | undefined,
  platforms: string[],
): string {
  if (!plan) return inferAppFormatFromPlatforms(platforms);
  const meta = getPlanMeta(plan);
  return meta.appFormatId ?? inferAppFormatFromPlatforms(platforms);
}

export function getPlanDefaultModules(plan: Plan | undefined): string[] {
  if (!plan) return [];
  return getPlanMeta(plan).defaultModules ?? [];
}

export function findPlanBySlug(plans: Plan[], slug: string): Plan | undefined {
  return plans.find((p) => p.slug === slug);
}

export function getPlanningDisplayPlans(plans: Plan[] | null | undefined): PlanDisplayCard[] {
  const list = Array.isArray(plans) ? plans : [];
  return list
    .filter((p) => p.active)
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map(planToDisplayCard);
}
