import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { Btn, cn } from "@/pages/app/components/ui";
import { BizTopBar } from "@/pages/app/components/biz/BizUI";
import { merchantProfile, merchantPhoneDisplay, myBusiness } from "@/mocks/dshnBusiness";
import type { ScreenId } from "@/pages/app/types";

interface SectionItem {
  icon: string;
  label: string;
  target: ScreenId;
}

const BUSINESS_SECTIONS: SectionItem[] = [
  { icon: "ri-eye-line", label: "معاينة صفحة المنشأة", target: "bizPreview" },
  { icon: "ri-store-3-line", label: "إدارة المنشأة", target: "bizManage" },
  { icon: "ri-line-chart-line", label: "فرص الاستثمار", target: "bizOpportunities" },
  { icon: "ri-user-received-line", label: "طلبات الاستثمار", target: "bizInvestRequests" },
  { icon: "ri-search-eye-line", label: "استكشاف المنشآت للشراكة", target: "bizPartnersExplore" },
  { icon: "ri-team-line", label: "الشراكات", target: "bizPartnerships" },
  { icon: "ri-wallet-3-line", label: "الأرباح والسحب", target: "bizEarnings" },
  { icon: "ri-receipt-line", label: "تسوية عمولات الاستثمار", target: "bizCommissions" },
  { icon: "ri-notification-3-line", label: "الإشعارات", target: "bizNotifications" },
];

const ACCOUNT_SECTIONS: SectionItem[] = [
  { icon: "ri-user-settings-line", label: "تعديل البيانات", target: "bizEditData" },
  { icon: "ri-settings-3-line", label: "الإعدادات", target: "bizSettings" },
];

const ROW =
  "w-full h-14 flex items-center gap-3 px-4 text-right cursor-pointer hover:bg-background-200/50 transition-colors";
const ICON_WRAP = "w-9 h-9 rounded-[11px] bg-background-200 flex items-center justify-center shrink-0";
const ICON = "text-[17px] text-foreground-800 leading-none";
const LABEL = "flex-1 min-w-0 text-[13.5px] font-medium text-foreground-900 truncate text-right";
const CHEVRON = "ri-arrow-left-s-line text-[18px] text-foreground-400 leading-none shrink-0";
const VALUE = "text-[12.5px] text-foreground-500 shrink-0";

function SectionRow({ icon, label, onClick }: { icon: string; label: string; onClick: () => void }) {
  return (
    <button type="button" onClick={onClick} className={ROW}>
      <span className={ICON_WRAP}>
        <i className={cn(icon, ICON)} />
      </span>
      <span className={LABEL}>{label}</span>
      <i className={CHEVRON} />
    </button>
  );
}

/**
 * Business-owner "حسابي" (profile) body — reusable by the profile page and by
 * the account popups (language / delete). Normal page flow, no position:fixed.
 *
 * `notifOn` reflects the notification toggle (ON = black).
 */
export function BizProfileBody({
  onLogout,
  notifOn = true,
}: {
  onLogout: () => void;
  notifOn?: boolean;
}) {
  const { navigate, lang } = useApp();

  return (
    <>
      <BizTopBar title="حسابي" />

      <div className="px-4 pt-5 pb-[104px]">
        {/* Profile card */}
        <div className="flex items-center gap-3 rounded-[20px] bg-background-100 border border-background-200 p-4">
          <div className="w-16 h-16 rounded-full overflow-hidden bg-background-200 shrink-0">
            <img
              src={merchantProfile.avatar}
              alt={merchantProfile.name}
              className="w-full h-full object-cover object-top"
            />
          </div>
          <div className="min-w-0">
            <p className="text-[16px] font-bold text-foreground-950 truncate">{merchantProfile.name}</p>
            <p className="text-[12.5px] text-foreground-600 mt-1" dir="ltr">
              {merchantProfile.phone}
            </p>
            <p className="text-[11.5px] text-foreground-500 mt-0.5 truncate">
              صاحب بيزنس · {myBusiness.name}
            </p>
          </div>
        </div>

        {/* Business sections */}
        <h2 className="mt-5 mb-2.5 text-[15px] font-semibold text-foreground-950">أقسام المنشأة</h2>
        <nav className="rounded-[20px] bg-background-100 border border-background-200 overflow-hidden divide-y divide-background-200">
          {BUSINESS_SECTIONS.map((s) => (
            <SectionRow key={s.label} icon={s.icon} label={s.label} onClick={() => navigate(s.target)} />
          ))}
        </nav>

        {/* Account sections */}
        <h2 className="mt-5 mb-2.5 text-[15px] font-semibold text-foreground-950">الحساب</h2>
        <nav className="rounded-[20px] bg-background-100 border border-background-200 overflow-hidden divide-y divide-background-200">
          {ACCOUNT_SECTIONS.map((s) => (
            <SectionRow key={s.label} icon={s.icon} label={s.label} onClick={() => navigate(s.target)} />
          ))}

          {/* تغيير رقم الجوال */}
          <button type="button" onClick={() => navigate("bizPhoneOld")} className={ROW}>
            <span className={ICON_WRAP}>
              <i className={cn("ri-smartphone-line", ICON)} />
            </span>
            <span className={LABEL}>تغيير رقم الجوال</span>
            <span className={VALUE} dir="ltr">
              {merchantPhoneDisplay}
            </span>
            <i className={CHEVRON} />
          </button>

          {/* تغيير اللغة */}
          <button type="button" onClick={() => navigate("bizLanguage")} className={ROW}>
            <span className={ICON_WRAP}>
              <i className={cn("ri-translate-2", ICON)} />
            </span>
            <span className={LABEL}>تغيير اللغة</span>
            <span className={VALUE}>{lang === "ar" ? "العربية" : "English"}</span>
            <i className={CHEVRON} />
          </button>

          {/* الإشعارات — ON/OFF toggle (black when on), no chevron */}
          <button
            type="button"
            onClick={() => navigate(notifOn ? "bizProfileNotifOff" : "bizProfile")}
            className={ROW}
          >
            <span className={ICON_WRAP}>
              <i className={cn("ri-notification-3-line", ICON)} />
            </span>
            <span className={LABEL}>الإشعارات</span>
            <span
              className={cn(
                "relative w-[48px] h-[28px] rounded-full shrink-0 transition-colors",
                notifOn ? "bg-foreground-950" : "bg-background-300",
              )}
              aria-hidden="true"
            >
              <span
                className={cn(
                  "absolute top-1 w-[20px] h-[20px] rounded-full bg-background-50 transition-all",
                  notifOn ? "right-1" : "right-[26px]",
                )}
              />
            </span>
          </button>
        </nav>

        {/* Logout — white bg, light red border, red text */}
        <button
          type="button"
          onClick={onLogout}
          className="mt-6 w-full h-[52px] rounded-[14px] bg-background-100 border border-danger-200 text-danger-600 text-[14.5px] font-semibold flex items-center justify-center gap-2 cursor-pointer hover:bg-danger-50 transition-colors whitespace-nowrap"
        >
          <i className="ri-logout-box-r-line text-[19px] leading-none" />
          تسجيل الخروج
        </button>

        {/* Delete account — red-tint row, last item */}
        <button
          type="button"
          onClick={() => navigate("bizDeleteAccount")}
          className="mt-3 w-full h-[60px] px-4 rounded-[18px] bg-danger-50 border border-danger-200 flex items-center gap-3.5 cursor-pointer hover:bg-danger-100 transition-colors"
        >
          <span className="w-10 h-10 rounded-[12px] bg-danger-100 flex items-center justify-center shrink-0">
            <i className="ri-delete-bin-6-line text-[19px] text-danger-700 leading-none" />
          </span>
          <span className="flex-1 text-right text-[14px] font-semibold text-danger-700">حذف الحساب</span>
          <i className="ri-arrow-left-s-line text-[20px] text-danger-400 leading-none shrink-0" />
        </button>
      </div>
    </>
  );
}

/** Business-owner profile page — body + logout confirmation popup. */
export function BizProfileScreen({ notifOn = true }: { notifOn?: boolean }) {
  const { navigate } = useApp();
  const [confirmOpen, setConfirmOpen] = useState(false);

  return (
    <div className="relative min-h-full bg-background-50">
      <BizProfileBody notifOn={notifOn} onLogout={() => setConfirmOpen(true)} />

      {confirmOpen && (
        <div className="absolute inset-0 z-40 flex items-center justify-center px-6 bg-foreground-950/40">
          <div className="w-full rounded-[20px] bg-background-100 border border-background-200 p-6">
            <div className="w-14 h-14 rounded-full bg-danger-50 flex items-center justify-center mx-auto mb-4">
              <i className="ri-logout-box-r-line text-[26px] text-danger-600 leading-none" />
            </div>
            <h3 className="text-[17px] font-bold text-foreground-950 text-center leading-relaxed">
              هل أنت متأكد من تسجيل الخروج؟
            </h3>
            <div className="mt-6 flex gap-3">
              <div className="flex-1">
                <Btn
                  variant="danger"
                  full
                  onClick={() => {
                    setConfirmOpen(false);
                    navigate("welcome");
                  }}
                >
                  تأكيد
                </Btn>
              </div>
              <div className="flex-1">
                <Btn variant="secondary" full onClick={() => setConfirmOpen(false)}>
                  إلغاء
                </Btn>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default function BizProfile() {
  return <BizProfileScreen />;
}