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 {
  investorInvestmentChanges,
  investorInvestmentNew,
  investorInvestmentRequest,
  investorProfile,
  investorSectors,
  investorTypes,
} from "@/mocks/dshnInvestor";

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

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

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

/**
 * The investor investment-profile editor. `variant="edit"` is the editable
 * form (submits for admin review); `variant="pending"` shows the same fields
 * read-only with a yellow "under review" banner and no submit.
 */
export default function InvestmentForm({ variant = "edit" }: { variant?: "edit" | "pending" }) {
  const readOnly = variant === "pending";
  const { goBack, navigate } = useApp();

  const [type, setType] = useState(
    readOnly ? investorInvestmentNew.typeLabel : investorProfile.typeLabel,
  );
  const [sectors, setSectors] = useState<string[]>(
    readOnly ? investorInvestmentNew.sectors : investorProfile.sectors,
  );
  const [minRange, setMinRange] = useState(
    readOnly ? String(investorInvestmentNew.minRange) : ORIGINAL.minRange,
  );
  const [maxRange, setMaxRange] = useState(
    readOnly ? String(investorInvestmentNew.maxRange) : ORIGINAL.maxRange,
  );
  const [country, setCountry] = useState(
    readOnly ? investorInvestmentNew.country : investorProfile.country,
  );
  const [bio, setBio] = useState(investorProfile.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(
    () =>
      type !== ORIGINAL.typeLabel ||
      country !== ORIGINAL.country ||
      bio !== ORIGINAL.bio ||
      minRange !== ORIGINAL.minRange ||
      maxRange !== ORIGINAL.maxRange ||
      !sameList(sectors, ORIGINAL.sectors),
    [type, country, bio, minRange, maxRange, sectors],
  );

  const valid =
    Boolean(type) &&
    sectors.length > 0 &&
    minRange !== "" &&
    maxRange !== "" &&
    Boolean(country) &&
    !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-4">
        {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">
                  أُرسل بتاريخ {investorInvestmentRequest.requestDate}
                </p>
              </div>
            </div>
            <div className="mt-3 space-y-2">
              {investorInvestmentChanges.map((c) => (
                <div key={c.label} className="flex items-center justify-between gap-3">
                  <span className="text-[11.5px] text-foreground-600">{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>
        )}

        <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="الدولة" required>
            <Select value={country} onChange={setCountry} options={COUNTRIES} />
          </Field>

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

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