import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { Btn, cn } from "@/pages/app/components/ui";
import { investorProfile } from "@/mocks/dshnInvestor";

/**
 * Investor "complete profile" body (section 3.2).
 * Shared by three separate pages so each exportable state stays in sync:
 *  - empty  → /investor-complete-profile        (partial, save disabled)
 *  - filled → /investor-complete-profile-filled (all filled, save enabled)
 *  - error  → /investor-complete-profile-error  (range error under the range fields)
 */

export type SetupVariant = "empty" | "filled" | "error";

/* Investment sectors (NOT product categories) — exactly the spec list */
const SECTORS = ["عقارات", "سيارات", "علامات تجارية/وكالات", "ابتكارات", "وغيرها"];
const TYPES = ["فرد", "جهة استثمارية"];
const COUNTRIES = [
  "المملكة العربية السعودية",
  "الإمارات العربية المتحدة",
  "دولة الكويت",
  "دولة قطر",
  "مملكة البحرين",
  "سلطنة عمان",
];

const onlyDigits = (v: string) => v.replace(/[^\d]/g, "");
const fmt = (v: string) => (v ? Number(v).toLocaleString("en-US") : "");

const inputBase =
  "w-full h-[52px] px-4 rounded-[13px] bg-background-100 border text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none transition-colors font-body";

function Label({ children, required }: { children: React.ReactNode; required?: boolean }) {
  return (
    <label className="block text-[12.5px] font-semibold text-foreground-900 mb-1.5">
      {children}
      {required && <span className="text-danger-500 mr-1">*</span>}
    </label>
  );
}

export default function InvProfileSetupBody({ variant = "empty" }: { variant?: SetupVariant }) {
  const { jump } = useApp();
  const filled = variant === "filled";
  const error = variant === "error";

  // Prefilled from registration
  const [name, setName] = useState(investorProfile.name);
  const [type, setType] = useState(investorProfile.typeLabel);
  const [sectors, setSectors] = useState<string[]>(
    filled ? ["عقارات", "علامات تجارية/وكالات", "ابتكارات"] : [],
  );
  const [minRange, setMinRange] = useState(filled || error ? "100000" : "");
  const [maxRange, setMaxRange] = useState(filled ? "1500000" : error ? "50000" : "");
  const [country, setCountry] = useState("المملكة العربية السعودية");
  const [bio, setBio] = useState(filled ? investorProfile.bio : "");

  const toggleSector = (s: string) =>
    setSectors((list) => (list.includes(s) ? list.filter((x) => x !== s) : [...list, s]));

  const rangeError = error && minRange !== "" && maxRange !== "" && Number(maxRange) <= Number(minRange);

  const valid =
    name.trim().length > 0 &&
    Boolean(type) &&
    sectors.length > 0 &&
    minRange !== "" &&
    maxRange !== "" &&
    Boolean(country) &&
    !(minRange !== "" && maxRange !== "" && Number(maxRange) <= Number(minRange));

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      {/* Sticky top bar — centered title, no back arrow (required step) */}
      <header className="sticky top-0 z-30 shrink-0 bg-background-50/95 backdrop-blur border-b border-background-200/70">
        <div className="px-4 pt-[calc(env(safe-area-inset-top)+0.75rem)] pb-3 text-center">
          <h1 className="text-[17px] font-bold text-foreground-950">استكمال الملف الشخصي</h1>
          <p className="text-[12px] text-foreground-600 mt-1 leading-relaxed">
            أكمل ملفك الاستثماري لتبدأ استكشاف المنصة
          </p>
        </div>
      </header>

      <div className="flex-1 px-4 py-5 space-y-5 pb-6">
        {/* 1. Name */}
        <div>
          <Label required>الاسم</Label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="الاسم الكامل"
            className={cn(inputBase, "border-background-200 focus:border-foreground-400")}
          />
        </div>

        {/* 2. Investor type — two equal segments */}
        <div>
          <Label required>نوع المستثمر</Label>
          <div className="grid grid-cols-2 gap-2.5">
            {TYPES.map((t) => (
              <button
                key={t}
                type="button"
                onClick={() => setType(t)}
                className={cn(
                  "h-[52px] rounded-[13px] border text-[13.5px] font-semibold cursor-pointer transition-colors whitespace-nowrap",
                  type === t
                    ? "bg-primary-500 text-background-50 border-primary-500"
                    : "bg-background-100 border-background-200 text-foreground-800 hover:border-foreground-300",
                )}
              >
                {t}
              </button>
            ))}
          </div>
        </div>

        {/* 3. Interested sectors — multi-select wrap chips */}
        <div>
          <Label required>القطاعات المهتم بها</Label>
          <div className="flex flex-wrap gap-2">
            {SECTORS.map((s) => {
              const active = sectors.includes(s);
              return (
                <button
                  key={s}
                  type="button"
                  onClick={() => toggleSector(s)}
                  className={cn(
                    "h-10 rounded-full px-3.5 inline-flex items-center text-[12.5px] font-medium cursor-pointer transition-colors whitespace-nowrap",
                    active
                      ? "bg-accent-500 text-accent-950"
                      : "bg-background-100 border border-background-200 text-foreground-700 hover:border-foreground-300",
                  )}
                >
                  {active && <i className="ri-check-line text-[14px] leading-none ml-1" />}
                  {s}
                </button>
              );
            })}
          </div>
          <p className="text-[11px] text-foreground-500 mt-1.5">اختر قطاعًا واحدًا أو أكثر</p>
        </div>

        {/* 4. Investment range — two fields + dash, thousands separators */}
        <div>
          <Label required>نطاق الاستثمار (ر.س)</Label>
          <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-end gap-2.5">
            <div className="min-w-0">
              <span className="block text-[11px] text-foreground-600 mb-1">الحد الأدنى</span>
              <input
                inputMode="numeric"
                dir="ltr"
                value={fmt(minRange)}
                onChange={(e) => setMinRange(onlyDigits(e.target.value))}
                placeholder="0"
                className={cn(
                  inputBase,
                  "text-left",
                  rangeError ? "border-danger-400 focus:border-danger-500" : "border-background-200 focus:border-foreground-400",
                )}
              />
            </div>
            <span className="h-[52px] flex items-center justify-center text-foreground-400">—</span>
            <div className="min-w-0">
              <span className="block text-[11px] text-foreground-600 mb-1">الحد الأقصى</span>
              <input
                inputMode="numeric"
                dir="ltr"
                value={fmt(maxRange)}
                onChange={(e) => setMaxRange(onlyDigits(e.target.value))}
                placeholder="0"
                className={cn(
                  inputBase,
                  "text-left",
                  rangeError ? "border-danger-400 focus:border-danger-500" : "border-background-200 focus:border-foreground-400",
                )}
              />
            </div>
          </div>
          {rangeError && (
            <p className="text-[11.5px] text-danger-600 mt-1.5">الحد الأقصى يجب أن يكون أكبر من الحد الأدنى</p>
          )}
        </div>

        {/* 5. Country */}
        <div>
          <Label required>الدولة</Label>
          <div className="relative">
            <select
              value={country}
              onChange={(e) => setCountry(e.target.value)}
              className={cn(inputBase, "appearance-none pl-10 cursor-pointer border-background-200 focus:border-foreground-400")}
            >
              {COUNTRIES.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
            <i className="ri-arrow-down-s-line text-[19px] text-foreground-500 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none leading-none" />
          </div>
        </div>

        {/* 6. Bio — optional, 4 lines, counter */}
        <div>
          <Label>نبذة عنك</Label>
          <textarea
            value={bio}
            onChange={(e) => setBio(e.target.value.slice(0, 300))}
            rows={4}
            placeholder="اكتب نبذة مختصرة عن خبرتك الاستثمارية واهتماماتك..."
            className="w-full px-4 py-3 rounded-[13px] bg-background-100 border border-background-200 text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body resize-none leading-relaxed"
          />
          <p className="text-[10.5px] text-foreground-500 text-left mt-1" dir="ltr">
            {bio.length}/300
          </p>
        </div>
      </div>

      {/* Sticky bottom bar — white, top hairline, 12px 16px + safe area */}
      <div className="sticky bottom-0 z-30 shrink-0 bg-background-100 border-t border-background-200/70 px-4 py-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)]">
        <Btn full disabled={!valid} onClick={() => jump("invHome")}>
          حفظ
        </Btn>
      </div>
    </div>
  );
}