"use client";

import type { ComponentType } from "react";
import type { CredentialMetaMap } from "@/lib/settings/credential-fields";
import {
  BarChart3,
  Bell,
  CreditCard,
  HardDrive,
  KeyRound,
  Lock,
  Mail,
  MapPin,
  MessagesSquare,
  Monitor,
  Palette,
  Shield,
  ShoppingBag,
  Sparkles,
  Store,
  Truck,
  Wrench,
} from "lucide-react";

export type AdminSettingsSectionId =
  | "general"
  | "appearance"
  | "marketplace"
  | "pos"
  | "locations"
  | "twoFactor"
  | "oauth"
  | "security"
  | "payment"
  | "email"
  | "notifications"
  | "messaging"
  | "orders"
  | "shipping"
  | "seo"
  | "social"
  | "analytics"
  | "maintenance"
  | "storage"
  | "aiAuthoring";

export type SectionStatus = "ok" | "warning" | "disabled";

export type AdminSettingsSection = {
  id: AdminSettingsSectionId;
  tab: AdminSettingsSectionId;
  labelKey: string;
  defaultLabel: string;
  icon: ComponentType<{ className?: string }>;
};

export const ADMIN_SETTINGS_SECTIONS: AdminSettingsSection[] = [
  {
    id: "general",
    tab: "general",
    labelKey: "admin.settings.general.title",
    defaultLabel: "General",
    icon: Store,
  },
  {
    id: "appearance",
    tab: "appearance",
    labelKey: "admin.settings.appearance.title",
    defaultLabel: "Branding",
    icon: Palette,
  },
  {
    id: "marketplace",
    tab: "marketplace",
    labelKey: "admin.settings.security.multiVendor.label",
    defaultLabel: "Multi-Vendor Management",
    icon: ShoppingBag,
  },
  {
    id: "pos",
    tab: "pos",
    labelKey: "admin.settings.pos.title",
    defaultLabel: "POS",
    icon: Monitor,
  },
  {
    id: "locations",
    tab: "locations",
    labelKey: "admin.settings.locations.title",
    defaultLabel: "Inventory Locations",
    icon: MapPin,
  },
  {
    id: "twoFactor",
    tab: "twoFactor",
    labelKey: "admin.settings.twoFactor.title",
    defaultLabel: "Two-Factor Authentication",
    icon: Lock,
  },
  {
    id: "oauth",
    tab: "oauth",
    labelKey: "admin.settings.oauth.title",
    defaultLabel: "OAuth / Social Login",
    icon: KeyRound,
  },
  {
    id: "aiAuthoring",
    tab: "aiAuthoring",
    labelKey: "admin.settings.ai.title",
    defaultLabel: "AI Configuration",
    icon: Sparkles,
  },
  {
    id: "security",
    tab: "security",
    labelKey: "admin.settings.security.title",
    defaultLabel: "Security & Access Control",
    icon: Shield,
  },
  {
    id: "payment",
    tab: "payment",
    labelKey: "admin.settings.payment.title",
    defaultLabel: "Payment Settings",
    icon: CreditCard,
  },
  {
    id: "email",
    tab: "email",
    labelKey: "admin.settings.email.title",
    defaultLabel: "Email Configuration (SMTP)",
    icon: Mail,
  },
  {
    id: "notifications",
    tab: "notifications",
    labelKey: "admin.settings.notifications.title",
    defaultLabel: "Notification Settings",
    icon: Bell,
  },
  {
    id: "messaging",
    tab: "messaging",
    labelKey: "admin.settings.messaging.title",
    defaultLabel: "Omnichannel Messaging",
    icon: MessagesSquare,
  },
  {
    id: "orders",
    tab: "orders",
    labelKey: "admin.settings.orders.title",
    defaultLabel: "Order Settings",
    icon: Wrench,
  },
  {
    id: "shipping",
    tab: "shipping",
    labelKey: "admin.settings.shipping.title",
    defaultLabel: "Shipping & Delivery",
    icon: Truck,
  },
  {
    id: "seo",
    tab: "seo",
    labelKey: "admin.settings.seo.title",
    defaultLabel: "SEO Settings",
    icon: BarChart3,
  },
  {
    id: "social",
    tab: "social",
    labelKey: "admin.settings.social.title",
    defaultLabel: "Social / Links",
    icon: Wrench,
  },
  {
    id: "analytics",
    tab: "analytics",
    labelKey: "admin.settings.analytics.title",
    defaultLabel: "Analytics",
    icon: BarChart3,
  },
  {
    id: "maintenance",
    tab: "maintenance",
    labelKey: "admin.settings.maintenance.title",
    defaultLabel: "Maintenance",
    icon: Wrench,
  },
  {
    id: "storage",
    tab: "storage",
    labelKey: "admin.settings.storage.title",
    defaultLabel: "Storage",
    icon: HardDrive,
  },
];

type SettingsForStatus = {
  maintenance?: { enabled?: boolean };
  payment?: {
    stripe?: { enabled?: boolean };
    paypal?: { enabled?: boolean };
    razorpay?: { enabled?: boolean };
    paystack?: { enabled?: boolean };
    pesapal?: { enabled?: boolean };
    iotec?: { enabled?: boolean };
  };
  email?: { enabled?: boolean; provider?: string; smtp?: { host?: string; user?: string } };
  shipping?: { enabled?: boolean; zones?: Array<{ rates?: unknown[] }> };
  storage?: { provider?: string; bucketName?: string };
  security?: {
    twoFactorEnabled?: boolean;
    googleOAuthEnabled?: boolean;
    facebookOAuthEnabled?: boolean;
  };
  aiAuthoring?: { enabled?: boolean };
  _meta?: {
    credentials?: CredentialMetaMap;
    envSources?: {
      ai?: { apiKey?: boolean };
      payment?: {
        stripe?: { publishableKey?: boolean; secretKey?: boolean };
        paypal?: { clientId?: boolean; clientSecret?: boolean };
        razorpay?: { keyId?: boolean; keySecret?: boolean };
        paystack?: { publicKey?: boolean; secretKey?: boolean };
        pesapal?: {
          consumerKey?: boolean;
          consumerSecret?: boolean;
          ipnId?: boolean;
        };
        iotec?: {
          clientId?: boolean;
          clientSecret?: boolean;
          walletId?: boolean;
        };
      };
      security?: {
        googleClientId?: boolean;
        googleClientSecret?: boolean;
        facebookAppId?: boolean;
        facebookAppSecret?: boolean;
      };
      storage?: { accessKeyId?: boolean };
    };
  };
};

export function getSectionStatus(
  sectionId: AdminSettingsSectionId,
  settings: SettingsForStatus,
): SectionStatus {
  if (sectionId === "maintenance") {
    return settings.maintenance?.enabled ? "warning" : "ok";
  }

  if (sectionId === "payment") {
    const cred = (path: string) =>
      Boolean(settings._meta?.credentials?.[path]?.set);
    const env = settings._meta?.envSources?.payment;

    const providers: Array<{ enabled: boolean; configured: boolean }> = [
      {
        enabled: settings.payment?.stripe?.enabled ?? false,
        configured:
          cred("payment.stripe.secretKey") || Boolean(env?.stripe?.secretKey),
      },
      {
        enabled: settings.payment?.paypal?.enabled ?? false,
        configured:
          cred("payment.paypal.clientSecret") ||
          Boolean(env?.paypal?.clientSecret),
      },
      {
        enabled: settings.payment?.razorpay?.enabled ?? false,
        configured:
          cred("payment.razorpay.keySecret") ||
          Boolean(env?.razorpay?.keySecret),
      },
      {
        enabled: settings.payment?.paystack?.enabled ?? false,
        configured:
          cred("payment.paystack.secretKey") ||
          Boolean(env?.paystack?.secretKey),
      },
      {
        enabled: settings.payment?.pesapal?.enabled ?? false,
        configured:
          (cred("payment.pesapal.consumerKey") ||
            Boolean(env?.pesapal?.consumerKey)) &&
          (cred("payment.pesapal.consumerSecret") ||
            Boolean(env?.pesapal?.consumerSecret)) &&
          (cred("payment.pesapal.ipnId") || Boolean(env?.pesapal?.ipnId)),
      },
      {
        enabled: settings.payment?.iotec?.enabled ?? false,
        configured:
          (cred("payment.iotec.clientId") || Boolean(env?.iotec?.clientId)) &&
          (cred("payment.iotec.clientSecret") ||
            Boolean(env?.iotec?.clientSecret)) &&
          (cred("payment.iotec.walletId") || Boolean(env?.iotec?.walletId)),
      },
    ];

    return providers.some((p) => p.enabled && !p.configured)
      ? "warning"
      : "ok";
  }

  if (sectionId === "email") {
    if (!settings.email?.enabled) return "disabled";
    if (settings.email.provider !== "smtp") return "ok";
    const host = settings.email.smtp?.host;
    const user = settings.email.smtp?.user;
    return !host || !user ? "warning" : "ok";
  }

  if (sectionId === "storage") {
    if (!settings.storage) return "ok";
    const bucketName = settings.storage.bucketName;
    const accessKeyId =
      settings._meta?.credentials?.["storage.accessKeyId"]?.set ||
      settings._meta?.envSources?.storage?.accessKeyId;
    return !bucketName || !accessKeyId ? "warning" : "ok";
  }

  if (sectionId === "oauth") {
    const googleEnabled = settings.security?.googleOAuthEnabled ?? false;
    const facebookEnabled = settings.security?.facebookOAuthEnabled ?? false;
    const oauthEnv = settings._meta?.envSources?.security;
    const oauthCred = (path: string) =>
      Boolean(settings._meta?.credentials?.[path]?.set);
    const googleConfigured =
      (oauthCred("security.googleClientId") ||
        Boolean(oauthEnv?.googleClientId)) &&
      (oauthCred("security.googleClientSecret") ||
        Boolean(oauthEnv?.googleClientSecret));
    const facebookConfigured =
      (oauthCred("security.facebookAppId") ||
        Boolean(oauthEnv?.facebookAppId)) &&
      (oauthCred("security.facebookAppSecret") ||
        Boolean(oauthEnv?.facebookAppSecret));
    const hasWarning =
      (googleEnabled && !googleConfigured) || (facebookEnabled && !facebookConfigured);
    return hasWarning ? "warning" : "ok";
  }

  if (sectionId === "twoFactor") {
    const enabled = settings.security?.twoFactorEnabled ?? false;
    return enabled ? "ok" : "disabled";
  }

  if (sectionId === "shipping") {
    const enabled = settings.shipping?.enabled ?? false;
    if (!enabled) return "disabled";
    const zones = settings.shipping?.zones ?? [];
    if (zones.length === 0) return "warning";
    const hasRates = zones.some((z) => Array.isArray(z.rates) && z.rates.length > 0);
    return hasRates ? "ok" : "warning";
  }

  if (sectionId === "aiAuthoring") {
    if (settings.aiAuthoring?.enabled === false) return "disabled";
    const keyAvailable =
      Boolean(settings._meta?.credentials?.["aiAuthoring.apiKey"]?.set) ||
      (settings._meta?.envSources?.ai?.apiKey ?? false);
    return keyAvailable ? "ok" : "warning";
  }

  return "ok";
}
