/**
 * SettingsPanel Component
 * Organization settings panel for dashboard including:
 * - Stripe payment configuration
 * - Language/Preferences settings
 * - Future: Other organization settings
 */

"use client";

import { useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import type { Lang } from "@/lib/config";
import dynamic from "next/dynamic";
import {
  CreditCard,
  Settings,
  Building2,
  Loader2,
  Globe,
  Check,
} from "lucide-react";

// Lazy load the Stripe form as it's a heavy component
const OrgStripeKeysForm = dynamic(
  () => import("./settings/OrgStripeKeysForm"),
  {
    loading: () => (
      <div className="flex items-center justify-center py-16">
        <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
      </div>
    ),
    ssr: false,
  },
);

interface SettingsPanelProps {
  lang: Lang;
}

type SettingsTab = "payment" | "preferences" | "organization";

export default function SettingsPanel({ lang }: SettingsPanelProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";
  const router = useRouter();
  const pathname = usePathname();
  const [activeTab, setActiveTab] = useState<SettingsTab>("payment");

  // Translations
  const t = {
    title: isAr ? "الإعدادات" : "Settings",
    subtitle: isAr
      ? "إدارة إعدادات مؤسستك"
      : "Manage your organization settings",
    paymentSettings: isAr ? "إعدادات الدفع" : "Payment Settings",
    paymentDesc: isAr
      ? "تكوين Stripe لقبول المدفوعات"
      : "Configure Stripe to accept payments",
    preferences: isAr ? "التفضيلات" : "Preferences",
    preferencesDesc: isAr
      ? "اللغة والإعدادات الشخصية"
      : "Language and personal settings",
    orgSettings: isAr ? "إعدادات المؤسسة" : "Organization",
    orgDesc: isAr ? "إعدادات المؤسسة العامة" : "General organization settings",
    comingSoon: isAr ? "قريباً" : "Coming Soon",
    orgSettingsComingSoon: isAr
      ? "إعدادات المؤسسة الإضافية ستكون متاحة قريباً."
      : "Additional organization settings will be available soon.",
    // Language settings
    language: isAr ? "اللغة" : "Language",
    languageDesc: isAr
      ? "اختر لغة العرض المفضلة لديك"
      : "Choose your preferred display language",
    english: "English",
    arabic: "العربية",
    currentLanguage: isAr ? "اللغة الحالية" : "Current Language",
    switchTo: isAr ? "التبديل إلى" : "Switch to",
    languageNote: isAr
      ? "سيتم تحديث الصفحة لتطبيق اللغة الجديدة"
      : "The page will refresh to apply the new language",
  };

  const tabs = [
    {
      id: "payment" as const,
      label: t.paymentSettings,
      description: t.paymentDesc,
      icon: <CreditCard className="w-5 h-5" />,
    },
    {
      id: "preferences" as const,
      label: t.preferences,
      description: t.preferencesDesc,
      icon: <Globe className="w-5 h-5" />,
    },
    {
      id: "organization" as const,
      label: t.orgSettings,
      description: t.orgDesc,
      icon: <Building2 className="w-5 h-5" />,
    },
  ];

  // Handle language change
  const handleLanguageChange = (newLang: "en" | "ar") => {
    if (newLang === lang) return;

    // Replace the language segment in the pathname
    const newPathname = pathname.replace(/^\/(en|ar)/, `/${newLang}`);
    router.push(newPathname + "?tab=settings");
  };

  return (
    <div className="space-y-6 animate-fadeIn" dir={dir}>
      {/* Header */}
      <div className="flex flex-col gap-2">
        <div
          className={`flex items-center gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <Settings className="w-7 h-7 text-brand-green" />
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
        </div>
        <p className="text-slate-600">{t.subtitle}</p>
      </div>

      {/* Tab Navigation */}
      <div
        className={`flex gap-2 border-b border-slate-200 pb-4 ${isAr ? "flex-row-reverse" : ""}`}
      >
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition-all ${
              activeTab === tab.id
                ? "bg-brand-green text-white shadow-lg shadow-brand-green/25"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200"
            } ${isAr ? "flex-row-reverse" : ""}`}
          >
            {tab.icon}
            <span>{tab.label}</span>
          </button>
        ))}
      </div>

      {/* Tab Content */}
      {activeTab === "payment" && <OrgStripeKeysForm lang={lang} />}

      {activeTab === "preferences" && (
        <div className="space-y-6">
          {/* Language Settings */}
          <div className="bg-white rounded-2xl border border-slate-200 p-6">
            <div
              className={`flex items-center gap-3 mb-6 ${isAr ? "flex-row-reverse" : ""}`}
            >
              <Globe className="w-6 h-6 text-brand-green" />
              <div>
                <h3 className="text-lg font-bold text-slate-900">
                  {t.language}
                </h3>
                <p className="text-sm text-slate-600">{t.languageDesc}</p>
              </div>
            </div>

            {/* Language Options */}
            <div className="grid gap-4 sm:grid-cols-2">
              {/* English Option */}
              <button
                onClick={() => handleLanguageChange("en")}
                className={`relative flex items-center gap-4 p-4 rounded-xl border-2 transition-all ${
                  lang === "en"
                    ? "border-brand-green bg-green-50"
                    : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                }`}
              >
                <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg flex items-center justify-center text-2xl">
                  🇬🇧
                </div>
                <div className={`flex-1 ${isAr ? "text-right" : "text-left"}`}>
                  <p className="font-semibold text-slate-900">{t.english}</p>
                  <p className="text-sm text-slate-500">English (LTR)</p>
                </div>
                {lang === "en" && (
                  <div className="absolute top-3 right-3 w-6 h-6 rounded-full bg-brand-green flex items-center justify-center">
                    <Check className="w-4 h-4 text-white" />
                  </div>
                )}
              </button>

              {/* Arabic Option */}
              <button
                onClick={() => handleLanguageChange("ar")}
                className={`relative flex items-center gap-4 p-4 rounded-xl border-2 transition-all ${
                  lang === "ar"
                    ? "border-brand-green bg-green-50"
                    : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                }`}
              >
                <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-green-500 to-emerald-600 shadow-lg flex items-center justify-center text-2xl">
                  🇸🇦
                </div>
                <div className={`flex-1 ${isAr ? "text-right" : "text-left"}`}>
                  <p className="font-semibold text-slate-900">{t.arabic}</p>
                  <p className="text-sm text-slate-500">العربية (RTL)</p>
                </div>
                {lang === "ar" && (
                  <div
                    className={`absolute top-3 ${isAr ? "left-3" : "right-3"} w-6 h-6 rounded-full bg-brand-green flex items-center justify-center`}
                  >
                    <Check className="w-4 h-4 text-white" />
                  </div>
                )}
              </button>
            </div>

            {/* Info Note */}
            <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-xl">
              <p className="text-sm text-blue-700">{t.languageNote}</p>
            </div>
          </div>
        </div>
      )}

      {activeTab === "organization" && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8">
          <div className="flex flex-col items-center justify-center text-center py-12">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <Building2 className="w-8 h-8 text-slate-400" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">
              {t.comingSoon}
            </h3>
            <p className="text-sm text-slate-500 max-w-md">
              {t.orgSettingsComingSoon}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
