import { useEffect, useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { useProductStore } from "@/pages/product/store";
import { BackHeader, Btn, cn } from "@/pages/app/components/ui";
import {
  Field,
  Select,
  Sheet,
  StepIndicator,
  TextArea,
  TextInput,
  UploadBox,
} from "@/pages/app/components/bo/BoUI";
import { bizCityOptions, businessFields, myBusiness } from "@/mocks/dshnBusiness";
import LocationMap, { type LatLng } from "@/pages/app/components/biz/LocationMap";

const CITIES = bizCityOptions;

type Step = 1 | 2 | 3;

const STEP_TITLE: Record<Step, string> = {
  1: "بيانات أساسية",
  2: "بيانات مالية",
  3: "استثمار وخطط نمو",
};

function MapPicker({
  open,
  onClose,
  onConfirm,
  pos,
  onPosChange,
}: {
  open: boolean;
  onClose: () => void;
  onConfirm: () => void;
  pos: LatLng;
  onPosChange: (v: LatLng) => void;
}) {
  return (
    <Sheet open={open} onClose={onClose}>
      <h3 className="text-[16px] font-bold text-foreground-950 mb-1">تحديد موقع المنشأة على الخريطة</h3>
      <p className="text-[12px] text-foreground-600 mb-3">اسحب الدبوس وثبّته على موقع منشأتك بدقة.</p>
      <LocationMap
        value={pos}
        onChange={onPosChange}
        draggable
        height={260}
        hint="اسحب الدبوس أو اضغط على الخريطة"
      />
      <div className="mt-4">
        <Btn full onClick={onConfirm}>
          تأكيد الموقع
        </Btn>
      </div>
    </Sheet>
  );
}

export default function BizSetup({ step }: { step: Step }) {
  const { jump, goBack } = useApp();
  const { bizSignup, beginBizSignupSetup, updateBusiness } = useProductStore();
  const signupProfile = bizSignup.profile;
  const [mapOpen, setMapOpen] = useState(false);
  const [locationSet, setLocationSet] = useState(false);
  const [pos, setPos] = useState<LatLng>({ lat: myBusiness.mapLat, lng: myBusiness.mapLng });

  // Entering the setup screens moves an approved registration into "جاري الإعداد".
  useEffect(() => {
    beginBizSignupSetup();
  }, [beginBizSignupSetup]);

  // step 1 — basic data (prefilled from the registration request)
  const [logo] = useState(Boolean(signupProfile.logoName));
  const [name, setName] = useState(signupProfile.businessName || "متجر النخبة");
  const [desc, setDesc] = useState("");
  const [field, setField] = useState("أغذية ومشروبات");
  const [founded, setFounded] = useState("2016");
  const [city, setCity] = useState(signupProfile.city || "الرياض");
  const [website, setWebsite] = useState("");
  const [social, setSocial] = useState("");

  // step 2 — financial data
  const [annualSales, setAnnualSales] = useState("");
  const [revenue, setRevenue] = useState("");
  const [currentValue, setCurrentValue] = useState("");
  const [lastValuation, setLastValuation] = useState("");
  const [lastValuationDate, setLastValuationDate] = useState("");

  // step 3 — investment & growth
  const [equity, setEquity] = useState("");
  const [amount, setAmount] = useState("");
  const [usage, setUsage] = useState("");
  const [growth, setGrowth] = useState("");
  const [docs, setDocs] = useState(false);
  const [deck, setDeck] = useState(false);

  const step1Valid = name.trim().length > 1 && Boolean(field) && Boolean(founded) && Boolean(city);
  const canNext = step === 1 ? step1Valid : true;

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title={STEP_TITLE[step]} subtitle="إكمال بيانات المنشأة" onBack={goBack} />

      <div className="px-5 pt-4">
        <StepIndicator current={step} total={3} />
      </div>

      <div className="flex-1 px-5 py-5 space-y-4">
        {step === 1 && (
          <>
            <div className="rounded-[16px] border border-accent-200 bg-accent-50 p-4">
              <p className="text-[12px] font-semibold text-foreground-800 flex items-center gap-1.5 mb-2">
                <i className="ri-shield-check-line text-[15px] text-accent-700 leading-none" />
                بيانات التحقق من الهوية التجارية (مرفوعة في التسجيل)
              </p>
              <div className="space-y-1.5">
                <div className="flex items-center justify-between gap-2 text-[11.5px]">
                  <span className="text-foreground-600">شعار المنشأة</span>
                  <span className="font-semibold text-foreground-900 flex items-center gap-1">
                    <i className={cn(logo ? "ri-checkbox-circle-fill text-accent-600" : "ri-error-warning-line text-danger-500", "text-[13px] leading-none")} />
                    {logo ? signupProfile.logoName : "غير مرفوع"}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-2 text-[11.5px]">
                  <span className="text-foreground-600">السجل التجاري</span>
                  <span className="font-semibold text-foreground-900" dir="ltr">
                    {signupProfile.crNumber || "—"}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-2 text-[11.5px]">
                  <span className="text-foreground-600">ضابط الاتصال</span>
                  <span className="font-semibold text-foreground-900 truncate">
                    {signupProfile.contactName || "—"}
                    {signupProfile.contactPhone ? ` · +966 ${signupProfile.contactPhone}` : ""}
                  </span>
                </div>
              </div>
            </div>

            <Field label="اسم المنشأة" required>
              <TextInput value={name} onChange={setName} placeholder="اسم المنشأة" />
            </Field>
            <Field label="وصف مختصر">
              <TextArea value={desc} onChange={setDesc} placeholder="اكتب نبذة قصيرة عن منشأتك ونشاطها..." rows={3} />
            </Field>
            <Field label="مجال العمل" required>
              <Select value={field} onChange={setField} options={businessFields} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="سنة التأسيس" required>
                <TextInput value={founded} onChange={(v) => setFounded(v.replace(/\D/g, "").slice(0, 4))} placeholder="2016" dir="ltr" />
              </Field>
              <Field label="المدينة / الدولة" required>
                <Select value={city} onChange={setCity} options={CITIES} />
              </Field>
            </div>

            <Field label="موقع المنشأة">
              <button
                type="button"
                onClick={() => setMapOpen(true)}
                className={cn(
                  "w-full rounded-[15px] border p-4 flex items-center gap-3 cursor-pointer text-right transition-colors",
                  locationSet
                    ? "border-accent-300 bg-accent-50"
                    : "border-dashed border-background-300 bg-background-100 hover:border-foreground-400",
                )}
              >
                <div
                  className={cn(
                    "w-11 h-11 rounded-[13px] flex items-center justify-center shrink-0",
                    locationSet ? "bg-accent-100 text-accent-800" : "bg-background-200 text-foreground-700",
                  )}
                >
                  <i className={cn(locationSet ? "ri-checkbox-circle-line" : "ri-map-pin-add-line", "text-[20px] leading-none")} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[13px] font-semibold text-foreground-950">
                    {locationSet ? "تم تحديد موقع المنشأة" : "تحديد موقع المنشأة على الخريطة"}
                  </p>
                  <p className="text-[11px] text-foreground-600 mt-0.5">
                    {locationSet ? "الرياض · حي الياسمين" : "اضغط لتثبيت الدبوس على موقع منشأتك"}
                  </p>
                </div>
                <i className="ri-arrow-left-s-line text-[20px] text-foreground-400 leading-none" />
              </button>
            </Field>

            <Field label="خريطة الموقع">
              <div className="rounded-[16px] border border-background-200 bg-background-100 p-2.5">
                <LocationMap
                  value={pos}
                  height={170}
                  className="rounded-[12px]"
                  hint="موقع منشأتك المحدد على الخريطة"
                />
                <div className="flex items-center gap-2 px-1.5 pt-3 pb-1">
                  <i className="ri-map-pin-2-line text-[16px] text-foreground-700 leading-none" />
                  <span className="flex-1 text-[12.5px] text-foreground-700">
                    {locationSet ? "حي الياسمين، طريق أنس بن مالك، الرياض" : "الرياض، المملكة العربية السعودية"}
                  </span>
                  <span className="text-[11px] text-foreground-600" dir="ltr">
                    {pos.lat.toFixed(4)}, {pos.lng.toFixed(4)}
                  </span>
                </div>
              </div>
            </Field>

            <Field label="الموقع الإلكتروني">
              <TextInput value={website} onChange={setWebsite} placeholder="www.example.sa" dir="ltr" />
            </Field>
            <Field label="وسائل التواصل">
              <TextInput value={social} onChange={setSocial} placeholder="@account" dir="ltr" />
            </Field>
          </>
        )}

        {step === 2 && (
          <>
            <Field label="المبيعات السنوية (ر.س)" hint="إجمالي المبيعات خلال آخر 12 شهرًا">
              <TextInput value={annualSales} onChange={(v) => setAnnualSales(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
            </Field>
            <Field label="حجم الإيرادات (ر.س)" hint="صافي الإيرادات بعد الخصومات">
              <TextInput value={revenue} onChange={(v) => setRevenue(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
            </Field>
            <Field label="القيمة الحالية للمنشأة (ر.س)">
              <TextInput value={currentValue} onChange={(v) => setCurrentValue(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="آخر تقييم (ر.س)">
                <TextInput value={lastValuation} onChange={(v) => setLastValuation(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
              </Field>
              <Field label="تاريخ آخر تقييم">
                <TextInput value={lastValuationDate} onChange={setLastValuationDate} placeholder="أغسطس 2025" />
              </Field>
            </div>
            <div className="flex items-start gap-2 rounded-[14px] bg-accent-50 border border-accent-200 px-3.5 py-3">
              <i className="ri-information-line text-[17px] text-accent-700 leading-none mt-0.5" />
              <span className="text-[11.5px] text-foreground-700 leading-relaxed">
                تُستخدم هذه البيانات في تقييم منشأتك وفرص الاستثمار، ويجب أن تكون مطابقة للمستندات الرسمية.
              </span>
            </div>
          </>
        )}

        {step === 3 && (
          <>
            <div className="grid grid-cols-2 gap-3">
              <Field label="نسبة استثمار متاحة (%)">
                <TextInput value={equity} onChange={(v) => setEquity(v.replace(/\D/g, "").slice(0, 2))} placeholder="20" dir="ltr" />
              </Field>
              <Field label="المبلغ المطلوب (ر.س)">
                <TextInput value={amount} onChange={(v) => setAmount(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
              </Field>
            </div>
            <Field label="غرض الاستثمار">
              <TextArea value={usage} onChange={setUsage} placeholder="كيف ستُستخدم قيمة الاستثمار؟" rows={3} />
            </Field>
            <Field label="نبذة خطط النمو">
              <TextArea value={growth} onChange={setGrowth} placeholder="اذكر خطط النمو والتوسع المستقبلية..." rows={3} />
            </Field>
            <UploadBox label="رفع صور ومستندات" hint="صور للمنشأة، قوائم مالية، إلخ" filled={docs} onToggle={() => setDocs((v) => !v)} />
            <UploadBox label="رفع Pitch Deck (اختياري)" hint="ملف عرض تقديمي PDF" icon="ri-file-ppt-2-line" filled={deck} onToggle={() => setDeck((v) => !v)} />
          </>
        )}
      </div>

      <div className="sticky bottom-0 z-30 px-5 py-5 bg-background-50 border-t border-background-200/70 flex gap-3">
        {step === 2 && (
          <div className="flex-1">
            <Btn full variant="secondary" onClick={() => jump("bizSetup1")}>
              رجوع
            </Btn>
          </div>
        )}
        <div className="flex-1">
          {step === 1 && (
            <Btn full disabled={!canNext} onClick={() => jump("bizSetup2")}>
              التالي
            </Btn>
          )}
          {step === 2 && (
            <Btn full onClick={() => jump("bizSetup3")}>
              التالي
            </Btn>
          )}
          {step === 3 && (
            <Btn
              full
              onClick={() => {
                updateBusiness({ name: name.trim() || myBusiness.name, city });
                jump("bizVerify");
              }}
            >
              حفظ ومتابعة للتوثيق
            </Btn>
          )}
        </div>
      </div>

      <MapPicker
        open={mapOpen}
        onClose={() => setMapOpen(false)}
        onConfirm={() => {
          setLocationSet(true);
          setMapOpen(false);
        }}
        pos={pos}
        onPosChange={setPos}
      />
    </div>
  );
}