import { useState, type ReactNode } from "react";
import { investorProfile } from "@/mocks/dshnInvestor";
import { useWeb } from "@/pages/web/WebContext";
import { Container, WCard, WBtn, WInput, StatusPill, cn, fmt } from "@/pages/web/WebUI";
import WebPageHeader from "@/pages/web/components/WebPageHeader";

export default function Profile() {
  const { t, role, logout, jump, isGuest, openAuth, lang, setLang } = useWeb();
  const [confirmLogout, setConfirmLogout] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);

  const isInvestor = role === "investor";
  const isBusiness = role === "business";
  const name = isInvestor ? investorProfile.name : isBusiness ? "عبدالله المطيري" : "سارة القحطاني";
  const phone = isInvestor ? investorProfile.phone : "+966 55 123 4567";
  const avatar = isInvestor
    ? investorProfile.avatar
    : "https://readdy.ai/api/search-image?query=Professional%20Saudi%20person%20portrait%20on%20light%20neutral%20background%2C%20minimal%20clean%20composition%2C%20soft%20natural%20light%2C%20corporate%20headshot%20photography%2C%20friendly%20expression&width=300&height=300&seq=dshn-web-user-avatar&orientation=squarish";
  const roleLabel = isInvestor ? t("roleInvestor") : isBusiness ? t("roleBusiness") : t("roleCustomer");

  const [formName, setFormName] = useState(name);
  const [formPhone, setFormPhone] = useState(phone);
  const [formCity, setFormCity] = useState("الرياض");

  if (isGuest) {
    return (
      <div className="relative animate-fade-in">
        <WebPageHeader title={t("account")} crumb={t("account")} />
        <Container className="py-16 max-w-[520px]">
          <WCard className="p-8 text-center">
            <span className="w-20 h-20 rounded-full bg-background-200 text-foreground-600 flex items-center justify-center mx-auto mb-6">
              <i className="ri-user-3-line text-[38px] leading-none" />
            </span>
            <h1 className="text-[22px] font-bold text-foreground-950 font-heading">أنت تتصفح كزائر</h1>
            <p className="text-[14px] text-foreground-600 mt-2 leading-relaxed">
              سجّل الدخول للوصول إلى حسابك ومفضلاتك وطلباتك وأدوات منشأتك أو استثماراتك.
            </p>
            <WBtn full className="w-full mt-6" icon="ri-login-box-line" onClick={() => openAuth("customer")}>
              {t("login")}
            </WBtn>
          </WCard>
        </Container>
      </div>
    );
  }

  return (
    <div className="relative animate-fade-in">
      <WebPageHeader title={t("account")} crumb={t("account")} />
      <Container className="py-8">
        <div className="flex flex-col lg:flex-row items-start gap-8">
          {/* settings menu (right in RTL) */}
          <aside className="w-full lg:w-[300px] shrink-0">
            <WCard className="p-5">
              <h3 className="text-[15px] font-bold text-foreground-950 mb-3">إعدادات الحساب</h3>
              <div className="space-y-1">
                <Row icon="ri-user-settings-line" label="تعديل البيانات" onClick={() => setEditOpen(true)} />
                <Row icon="ri-file-list-3-line" label={t("myOrders")} onClick={() => jump("orders")} />
                <Row icon="ri-notification-3-line" label={t("notifications")} onClick={() => jump("notifications")} />
                <Row icon="ri-heart-line" label={t("favorites")} onClick={() => jump("favorites")} />
                <Row icon="ri-chat-3-line" label={t("chats")} onClick={() => jump("chats")} />
                {isInvestor && <Row icon="ri-hand-coin-line" label={t("invFollowing")} onClick={() => jump("invFollowing")} />}
                {isBusiness && <Row icon="ri-dashboard-line" label={t("boDashboard")} onClick={() => jump("bo")} />}
              </div>

              <div className="mt-4 pt-4 border-t border-background-200">
                <p className="text-[12.5px] font-semibold text-foreground-800 mb-2.5">{t("language")}</p>
                <div className="flex items-center rounded-full bg-background-200 p-0.5 w-max text-[12.5px] font-semibold">
                  <button
                    type="button"
                    onClick={() => setLang("ar")}
                    className={cn("px-3.5 h-8 rounded-full cursor-pointer transition-colors", lang === "ar" ? "bg-primary-500 text-background-50" : "text-foreground-600")}
                  >
                    العربية
                  </button>
                  <button
                    type="button"
                    onClick={() => setLang("en")}
                    className={cn("px-3.5 h-8 rounded-full cursor-pointer transition-colors", lang === "en" ? "bg-primary-500 text-background-50" : "text-foreground-600")}
                  >
                    English
                  </button>
                </div>
              </div>

              <div className="mt-4 pt-4 border-t border-background-200 space-y-2">
                <button
                  type="button"
                  onClick={() => setConfirmLogout(true)}
                  className="w-full h-11 rounded-[12px] border border-background-200 bg-background-50 text-foreground-800 text-[14px] font-semibold flex items-center justify-center gap-2 cursor-pointer hover:bg-background-200"
                >
                  <i className="ri-logout-box-r-line text-[18px] leading-none" />
                  {t("logout")}
                </button>
                <button
                  type="button"
                  onClick={() => setDeleteOpen(true)}
                  className="w-full h-11 rounded-[12px] border border-danger-200 bg-danger-50 text-danger-700 text-[14px] font-semibold flex items-center justify-center gap-2 cursor-pointer hover:bg-danger-100"
                >
                  <i className="ri-delete-bin-6-line text-[18px] leading-none" />
                  حذف الحساب
                </button>
              </div>
            </WCard>
          </aside>

          {/* content (left in RTL) */}
          <div className="flex-1 min-w-0 space-y-6">
            <WCard className="p-6">
              <div className="flex items-center gap-5">
                <div className="w-[84px] h-[84px] rounded-full overflow-hidden bg-background-200 shrink-0">
                  <img src={avatar} alt={name} className="w-full h-full object-cover object-top" />
                </div>
                <div className="min-w-0">
                  <h1 className="text-[22px] font-bold text-foreground-950 font-heading break-words">{name}</h1>
                  <p className="text-[13.5px] text-foreground-600 mt-1" dir="ltr">{phone}</p>
                  <div className="mt-2 flex items-center gap-2 flex-wrap">
                    <StatusPill tone="info" icon="ri-shield-user-line">{roleLabel}</StatusPill>
                    <StatusPill tone="success" icon="ri-checkbox-circle-line">موثّق</StatusPill>
                  </div>
                </div>
                <WBtn variant="secondary" className="ms-auto hidden sm:inline-flex" icon="ri-edit-line" onClick={() => setEditOpen(true)}>
                  تعديل
                </WBtn>
              </div>
            </WCard>

            {isInvestor && (
              <WCard className="p-6">
                <h2 className="text-[17px] font-bold text-foreground-950 mb-4">الملف الاستثماري</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  <Info label="نوع المستثمر" value={investorProfile.typeLabel} />
                  <Info label="الدولة" value={investorProfile.country} />
                  <Info label="نطاق الاستثمار" value={`${fmt(investorProfile.minRange)} - ${fmt(investorProfile.maxRange)} ر.س`} />
                  <Info label="المدينة" value={investorProfile.city} />
                </div>
                <div className="mt-5">
                  <p className="text-[12.5px] font-semibold text-foreground-800 mb-2.5">القطاعات المهتم بها</p>
                  <div className="flex flex-wrap gap-2">
                    {investorProfile.sectors.map((s) => (
                      <span key={s} className="rounded-full bg-secondary-100 text-secondary-900 px-3.5 py-1.5 text-[12px] font-medium">{s}</span>
                    ))}
                  </div>
                </div>
                <div className="mt-5">
                  <p className="text-[12.5px] font-semibold text-foreground-800 mb-2">نبذة</p>
                  <p className="text-[13.5px] text-foreground-700 leading-relaxed">{investorProfile.bio}</p>
                </div>
              </WCard>
            )}

            {isBusiness && (
              <WCard className="p-6">
                <h2 className="text-[17px] font-bold text-foreground-950 mb-4">منشأتي</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  <Info label="اسم المنشأة" value="متجر النخبة" />
                  <Info label="النشاط" value="أغذية ومشروبات" />
                  <Info label="المدينة" value="الرياض" />
                  <Info label="سنة التأسيس" value="2019" />
                </div>
                <WBtn className="w-full mt-5" icon="ri-dashboard-line" onClick={() => jump("bo")}>
                  لوحة تحكم المنشأة
                </WBtn>
              </WCard>
            )}

            {!isInvestor && !isBusiness && (
              <WCard className="p-6">
                <h2 className="text-[17px] font-bold text-foreground-950 mb-4">ملفي</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  <Info label="المدينة" value="الرياض" />
                  <Info label="الحي" value="حي الملقا" />
                </div>
              </WCard>
            )}
          </div>
        </div>
      </Container>

      {/* logout confirm */}
      {confirmLogout && (
        <Modal onClose={() => setConfirmLogout(false)}>
          <h3 className="text-[18px] font-bold text-foreground-950 font-heading text-center">{t("logoutConfirm")}</h3>
          <div className="flex gap-3 mt-6">
            <WBtn className="flex-1" variant="secondary" onClick={() => setConfirmLogout(false)}>{t("cancel")}</WBtn>
            <WBtn
              className="flex-1"
              variant="danger"
              onClick={() => {
                setConfirmLogout(false);
                logout();
                jump("home");
              }}
            >
              {t("confirm")}
            </WBtn>
          </div>
        </Modal>
      )}

      {/* edit data */}
      {editOpen && (
        <Modal onClose={() => setEditOpen(false)}>
          <div className="flex items-center justify-between mb-5">
            <h3 className="text-[19px] font-bold text-foreground-950 font-heading">تعديل البيانات</h3>
            <button type="button" onClick={() => setEditOpen(false)} className="w-9 h-9 rounded-full hover:bg-background-200 flex items-center justify-center cursor-pointer">
              <i className="ri-close-line text-[20px] leading-none" />
            </button>
          </div>
          <div className="space-y-4">
            <Labelled label={t("fullName")}>
              <WInput value={formName} onChange={setFormName} />
            </Labelled>
            <Labelled label="رقم الجوال">
              <WInput value={formPhone} onChange={setFormPhone} dir="ltr" />
            </Labelled>
            <Labelled label={t("city")}>
              <WInput value={formCity} onChange={setFormCity} />
            </Labelled>
          </div>
          <p className="text-[12px] text-foreground-500 mt-4">تُرسل التعديلات للمراجعة قبل اعتمادها على حسابك.</p>
          <div className="flex gap-3 mt-6">
            <WBtn className="flex-1" variant="secondary" onClick={() => setEditOpen(false)}>{t("cancel")}</WBtn>
            <WBtn className="flex-1" onClick={() => setEditOpen(false)}>إرسال التعديل</WBtn>
          </div>
        </Modal>
      )}

      {/* delete account — blocked */}
      {deleteOpen && (
        <Modal onClose={() => setDeleteOpen(false)}>
          <div className="text-center">
            <span className="w-16 h-16 rounded-full bg-danger-50 text-danger-600 flex items-center justify-center mx-auto mb-5">
              <i className="ri-lock-2-line text-[32px] leading-none" />
            </span>
            <h3 className="text-[19px] font-bold text-foreground-950 font-heading">لا يمكن حذف الحساب حاليًا</h3>
            <p className="text-[13.5px] text-foreground-600 mt-2 leading-relaxed">
              لديك طلبات أو التزامات نشطة. أكملها أو ألغِها أولًا ثم يمكنك حذف الحساب نهائيًا.
            </p>
            <WBtn full className="w-full mt-6" onClick={() => setDeleteOpen(false)}>حسنًا، فهمت</WBtn>
          </div>
        </Modal>
      )}
    </div>
  );
}

function Modal({ children, onClose }: { children: ReactNode; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 animate-fade-in" onClick={onClose}>
      <div className="w-full max-w-[480px] bg-background-50 rounded-[20px] border border-background-200 p-6 animate-fade-up" onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
}

function Labelled({ label, children }: { label: string; children: ReactNode }) {
  return (
    <label className="block">
      <span className="block text-[13px] font-semibold text-foreground-800 mb-1.5">{label}</span>
      {children}
    </label>
  );
}

function Info({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-[14px] bg-background-50 border border-background-200 p-4">
      <p className="text-[12px] text-foreground-600">{label}</p>
      <p className="text-[15px] font-bold text-foreground-950 mt-1">{value}</p>
    </div>
  );
}

function Row({ icon, label, onClick }: { icon: string; label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="w-full h-11 px-3 rounded-[12px] flex items-center gap-2.5 text-[13.5px] font-medium text-foreground-800 hover:bg-background-200 cursor-pointer transition-colors"
    >
      <i className={cn(icon, "text-[18px] leading-none")} />
      {label}
      <i className="ri-arrow-left-s-line text-[18px] text-foreground-400 leading-none ms-auto" />
    </button>
  );
}