import { useMemo, useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn, cn } from "@/pages/app/components/ui";
import { Field, Select, TextArea, TextInput } from "@/pages/app/components/bo/BoUI";
import {
  investorCityOptions,
  investorEditDataChanges,
  investorEditDataNew,
  investorEditDataRequest,
  investorProfile,
  investorSectors,
  investorTypes,
} from "@/mocks/dshnInvestor";

const COUNTRIES = ["السعودية", "الإمارات", "الكويت", "قطر", "البحرين"];

const ORIGINAL = {
  name: investorProfile.name,
  city: investorProfile.city,
  country: investorProfile.country,
  typeLabel: investorProfile.typeLabel,
  sectors: investorProfile.sectors,
  minRange: String(investorProfile.minRange),
  maxRange: String(investorProfile.maxRange),
  bio: investorProfile.bio,
};

const sameList = (a: string[], b: string[]) =>
  a.slice().sort().join("|") === b.slice().sort().join("|");

/**
 * Unified "تعديل البيانات" editor — personal data + investment profile in one
 * form. `variant="edit"` is editable and submits for admin review;
 * `variant="pending"` shows the same fields read-only with a yellow
 * "under review" banner and no submit.
 */
export default function EditDataForm({ variant = "edit" }: { variant?: "edit" | "pending" }) {
  const readOnly = variant === "pending";
  const { goBack, navigate } = useApp();

  const [name, setName] = useState(readOnly ? investorEditDataNew.name : ORIGINAL.name);
  const [city, setCity] = useState(readOnly ? investorEditDataNew.city : ORIGINAL.city);
  const [country, setCountry] = useState(readOnly ? investorEditDataNew.country : ORIGINAL.country);
  const [type, setType] = useState(readOnly ? investorEditDataNew.typeLabel : ORIGINAL.typeLabel);
  const [sectors, setSectors] = useState<string[]>(
    readOnly ? investorEditDataNew.sectors : ORIGINAL.sectors,
  );
  const [minRange, setMinRange] = useState(
    readOnly ? String(investorEditDataNew.minRange) : ORIGINAL.minRange,
  );
  const [maxRange, setMaxRange] = useState(
    readOnly ? String(investorEditDataNew.maxRange) : ORIGINAL.maxRange,
  );
  const [bio, setBio] = useState(ORIGINAL.bio);

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

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

  const dirty = useMemo(
    () =>
      name.trim() !== ORIGINAL.name ||
      city !== ORIGINAL.city ||
      country !== ORIGINAL.country ||
      type !== ORIGINAL.typeLabel ||
      minRange !== ORIGINAL.minRange ||
      maxRange !== ORIGINAL.maxRange ||
      bio !== ORIGINAL.bio ||
      !sameList(sectors, ORIGINAL.sectors),
    [name, city, country, type, minRange, maxRange, bio, sectors],
  );

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

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="تعديل البيانات" onBack={goBack} />

      <div className="flex-1 px-5 py-5 space-y-5">
        {readOnly ? (
          <div className="rounded-[16px] bg-secondary-50 border border-secondary-300 p-4">
            <div className="flex items-center gap-2.5">
              <span className="w-9 h-9 rounded-[11px] bg-secondary-100 flex items-center justify-center shrink-0">
                <i className="ri-time-line text-[18px] text-secondary-800 leading-none" />
              </span>
              <div className="min-w-0">
                <p className="text-[13.5px] font-bold text-foreground-950">
                  لديك طلب تعديل قيد المراجعة
                </p>
                <p className="text-[11px] text-foreground-600 mt-0.5">
                  أُرسل بتاريخ {investorEditDataRequest.requestDate}
                </p>
              </div>
            </div>
            <div className="mt-3 space-y-2">
              {investorEditDataChanges.map((c) => (
                <div key={c.label} className="flex items-center justify-between gap-3">
                  <span className="text-[11.5px] text-foreground-600 shrink-0">{c.label}</span>
                  <span className="text-[12px] font-semibold text-foreground-900 text-left">{c.to}</span>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="flex items-start gap-2 rounded-[14px] bg-background-200/70 px-3.5 py-3">
            <i className="ri-information-line text-[16px] text-foreground-500 leading-none mt-0.5 shrink-0" />
            <p className="text-[11.5px] text-foreground-600 leading-relaxed">
              تخضع التعديلات لمراجعة الإدارة قبل اعتمادها
            </p>
          </div>
        )}

        {/* Section — personal data */}
        <section>
          <h2 className="text-[14px] font-bold text-foreground-950 mb-3">البيانات الشخصية</h2>
          <div className={cn("space-y-4", readOnly && "pointer-events-none opacity-70")}>
            <Field label="الاسم الكامل" required>
              <TextInput value={name} onChange={setName} placeholder="الاسم الكامل" />
            </Field>
            <Field label="المدينة" required>
              <Select value={city} onChange={setCity} options={investorCityOptions} placeholder="اختر المدينة" />
            </Field>
            <Field label="الدولة" required>
              <Select value={country} onChange={setCountry} options={COUNTRIES} />
            </Field>
          </div>
        </section>

        <div className="h-px bg-background-200" />

        {/* Section — investment profile */}
        <section>
          <h2 className="text-[14px] font-bold text-foreground-950 mb-3">الملف الاستثماري</h2>
          <div className={cn("space-y-4", readOnly && "pointer-events-none opacity-70")}>
            <Field label="نوع المستثمر" required>
              <div className="grid grid-cols-2 gap-2.5">
                {investorTypes.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",
                      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>
            </Field>

            <Field label="القطاعات المهتم بها" hint="اختر قطاعًا واحدًا أو أكثر">
              <div className="flex flex-wrap gap-2">
                {investorSectors.map((s) => {
                  const active = sectors.includes(s);
                  return (
                    <button
                      key={s}
                      type="button"
                      onClick={() => toggleSector(s)}
                      className={cn(
                        "rounded-full px-3.5 py-2 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>
            </Field>

            <Field label="نطاق الاستثمار (ر.س)" hint="حدّد الحد الأدنى والأعلى">
              <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-2.5">
                <TextInput
                  value={minRange}
                  onChange={(v) => setMinRange(v.replace(/\D/g, ""))}
                  placeholder="الحد الأدنى"
                  dir="ltr"
                />
                <TextInput
                  value={maxRange}
                  onChange={(v) => setMaxRange(v.replace(/\D/g, ""))}
                  placeholder="الحد الأقصى"
                  dir="ltr"
                />
              </div>
              {rangeInvalid && (
                <div className="flex items-center gap-1.5 mt-2 text-danger-600">
                  <i className="ri-error-warning-line text-[15px] leading-none" />
                  <span className="text-[12px] font-medium">
                    الحد الأقصى يجب أن يكون أكبر من الحد الأدنى
                  </span>
                </div>
              )}
            </Field>

            <Field label="نبذة عنك">
              <TextArea
                value={bio}
                onChange={setBio}
                placeholder="اكتب نبذة مختصرة عن خبرتك الاستثمارية واهتماماتك..."
                rows={4}
              />
            </Field>
          </div>
        </section>
      </div>

      {!readOnly && (
        <div className="px-5 py-5 pb-[calc(env(safe-area-inset-bottom)+1.25rem)]">
          <Btn full disabled={!dirty || !valid} onClick={() => navigate("invEditConfirm")}>
            إرسال طلب التعديل
          </Btn>
        </div>
      )}
    </div>
  );
}