"use client";
import { useState, type SubmitEvent } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  useForm,
  type FieldErrors,
  type Resolver,
  type UseFormRegister,
  type UseFormSetValue,
} from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object } from "yup";
import { useValidation } from "@/hooks/useValidation";
import { useProviderStats } from "@/hooks/useProviderStats";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { useAuthStore } from "@/lib/auth/store";
import type { AuthInfo } from "@/lib/auth/store";
import type { ProfitRateValue } from "@/lib/profitRate";
import FileDropzone from "@/components/shared/FileDropzone";
import AuthPasswordInput from "@/components/auth/AuthPasswordInput";
import LegalContentModal from "@/components/auth/LegalContentModal";
import {
  fieldBorderClass,
  formatFileSize,
  getFileKey,
  isAllowedUpload,
} from "@/lib/upload/fileUtils";

// ---------------------------------------------------------------------------
// DocumentsUpload: single dropzone multi-file uploader
// ---------------------------------------------------------------------------
function DocumentsUpload({
  files,
  onAddFile,
  onRemoveFile,
}: Readonly<{
  files: File[];
  onAddFile: (f: File) => void;
  onRemoveFile: (index: number) => void;
}>) {
  const handleFile = (file: File) => {
    if (!isAllowedUpload(file)) {
      return;
    }
    onAddFile(file);
  };

  return (
    <div className="border-t border-white/8 pt-4">
      <div className="flex items-center gap-2 mb-3">
        <div className="w-8 h-8 bg-[#FCD704]/15 rounded-lg flex items-center justify-center flex-shrink-0">
          <i className="ri-file-list-3-line text-[#FCD704]" />
        </div>
        <div>
          <p className="text-white text-xs font-bold">المستندات المطلوبة</p>
          <p className="text-gray-500 text-xs">
            ارفع المستندات التالية للتحقق من هويتك
          </p>
        </div>
      </div>

      <FileDropzone onFile={handleFile}>
        <div className="w-12 h-12 bg-white/5 rounded-lg flex items-center justify-center mb-2">
          <img
            src="/imgs/upload-icon.svg"
            alt="Upload"
            className="w-6 h-6 object-contain"
          />
        </div>
        <p className="text-white text-xs font-semibold">ارفق المستندات</p>
        <p className="text-gray-500 text-[11px]">
          اسحب أو اضغط للرفع • PDF, JPG, PNG
        </p>
      </FileDropzone>

      <div className="flex items-center gap-2 mt-2 ">
        <i className="ri-information-line text-gray-500 text-sm" />
        <p className="text-gray-500 text-xs">
          الحجم الأقصى لكل ملف 10 ميجا • PDF, JPG, PNG
        </p>
      </div>

      {files.length > 0 && (
        <div className="flex flex-col gap-2 mt-4">
          {files.map((file, idx) => (
            <div
              key={getFileKey(file)}
              className="flex items-center gap-3 p-3 bg-white/3 border border-white/5 rounded-xl "
            >
              <div className="w-9 h-9 bg-[#FCD704]/15 rounded-lg flex items-center justify-center flex-shrink-0">
                <i className="ri-file-check-line text-[#FCD704] text-lg" />
              </div>
              <div className="text-right flex-1 min-w-0">
                <p className="text-white text-xs font-semibold truncate">
                  {file.name}
                </p>
                <p className="text-gray-500 text-xs">
                  {formatFileSize(file.size)}
                </p>
              </div>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onRemoveFile(idx);
                }}
                className="w-7 h-7 bg-red-500/15 hover:bg-red-500/30 rounded-lg flex items-center justify-center flex-shrink-0 transition-colors cursor-pointer"
              >
                <i className="ri-delete-bin-line text-red-400 text-sm" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

interface SignupData {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  password: string;
  password_confirmation: string;
  national_id: string;
  iban: string;
  vehicle_count: string;
  documents: File[];
  terms_accepted: boolean;
}

function SignupSuccessScreen() {
  return (
    <div className="flex flex-col w-full max-w-md mx-auto">
      <div className="flex flex-col items-center text-center py-8">
        <div className="w-20 h-20 bg-[#FCD704]/15 border-2 border-[#FCD704]/40 rounded-full flex items-center justify-center mb-6">
          <i className="ri-checkbox-circle-fill text-[#FCD704] text-4xl" />
        </div>
        <h2 className="text-white font-bold text-2xl mb-2">تم إنشاء الحساب!</h2>
        <p className="text-gray-400 text-sm mb-2">مرحباً بك في منصة BEEBPEEP</p>
        <div className="bg-[#1E2128] rounded-2xl p-4 w-full mt-4 mb-6">
          <p className="text-gray-400 text-xs mb-1 text-right">
            الخطوة التالية
          </p>
          <p className="text-white text-sm text-right">
            سيتواصل معك فريقنا خلال 24 ساعة لتفعيل حساب المستثمر
          </p>
        </div>
        <Link
          href="/login"
          className="w-full bg-[#FCD704] text-[#13151A] font-bold text-base py-4 rounded-xl cursor-pointer text-center block"
        >
          تسجيل الدخول
        </Link>
      </div>
    </div>
  );
}

function SignupStepper({ step }: Readonly<{ step: 1 | 2 }>) {
  return (
    <div className="flex items-center justify-between gap-4 mb-8 w-full select-none">
      <div className="flex items-center justify-between gap-3 grow">
        <div className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold bg-[#FCD704]/20 border border-[#FCD704] text-[#FCD704]">
          1
        </div>
        <div
          className={`min-w-12 h-1 grow rounded-full transition-all ${step === 2 ? "bg-[#FCD704]" : "bg-white/10"}`}
        />
        <div
          className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold transition-all ${
            step === 2
              ? "bg-[#FCD704]/20 border border-[#FCD704] text-[#FCD704]"
              : "bg-white/5 border border-white/10 text-gray-500"
          }`}
        >
          2
        </div>
      </div>
      <span className="text-gray-400 text-xs font-semibold">
        {step === 1 ? "البيانات الأساسية" : "بيانات الاستثمار"}
      </span>
    </div>
  );
}

function SignupStepOneFields({
  register,
  errors,
  show,
  showConfirm,
  onToggleShow,
  onToggleShowConfirm,
}: Readonly<{
  register: UseFormRegister<SignupData>;
  errors: FieldErrors<SignupData>;
  show: boolean;
  showConfirm: boolean;
  onToggleShow: () => void;
  onToggleShowConfirm: () => void;
}>) {
  return (
    <div key="step-1" className="flex flex-col gap-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label
            htmlFor="signup-first-name"
            className="text-gray-400 text-xs block mb-2 text-right"
          >
            الاسم الأول
          </label>
          <input
            id="signup-first-name"
            {...register("first_name")}
            placeholder="أحمد"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 outline-none transition-colors text-right placeholder-gray-600 ${fieldBorderClass(!!errors.first_name)}`}
            dir="rtl"
          />
          {errors.first_name && (
            <p className="text-red-400 text-xs mt-1.5 text-right">
              {errors.first_name.message}
            </p>
          )}
        </div>
        <div>
          <label
            htmlFor="signup-last-name"
            className="text-gray-400 text-xs block mb-2 text-right"
          >
            الاسم الأخير
          </label>
          <input
            id="signup-last-name"
            {...register("last_name")}
            placeholder="المستثمر"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 outline-none transition-colors text-right placeholder-gray-600 ${fieldBorderClass(!!errors.last_name)}`}
            dir="rtl"
          />
          {errors.last_name && (
            <p className="text-red-400 text-xs mt-1.5 text-right">
              {errors.last_name.message}
            </p>
          )}
        </div>
      </div>

      <div>
        <label
          htmlFor="signup-email"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          البريد الإلكتروني
        </label>
        <div className="relative">
          <input
            id="signup-email"
            type="email"
            {...register("email")}
            placeholder="ahmed@beepbeep.sa"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 pr-12 outline-none transition-colors text-right placeholder-gray-600 ${fieldBorderClass(!!errors.email)}`}
            dir="rtl"
          />
          <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center pointer-events-none">
            <i className="ri-mail-line text-gray-500" />
          </div>
        </div>
        {errors.email && (
          <p className="text-red-400 text-xs mt-1.5 text-right">
            {errors.email.message}
          </p>
        )}
      </div>

      <div>
        <label
          htmlFor="signup-phone"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          رقم الجوال
        </label>
        <div className="relative">
          <input
            id="signup-phone"
            type="tel"
            {...register("phone")}
            placeholder="+966 5X XXX XXXX"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 pr-12 outline-none transition-colors text-right placeholder-gray-600 ${fieldBorderClass(!!errors.phone)}`}
            dir="rtl"
          />
          <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center pointer-events-none select-none">
            <span className="text-sm">🇸🇦</span>
          </div>
        </div>
        {errors.phone && (
          <p className="text-red-400 text-xs mt-1.5 text-right">
            {errors.phone.message}
          </p>
        )}
      </div>

      <div>
        <label
          htmlFor="signup-password"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          كلمة المرور
        </label>
        <AuthPasswordInput
          id="signup-password"
          show={show}
          onToggleShow={onToggleShow}
          registration={register("password")}
          hasError={!!errors.password}
          errorMessage={errors.password?.message}
          placeholder="8 أحرف على الأقل"
        />
      </div>

      <div>
        <label
          htmlFor="signup-password-confirmation"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          تأكيد كلمة المرور
        </label>
        <AuthPasswordInput
          id="signup-password-confirmation"
          show={showConfirm}
          onToggleShow={onToggleShowConfirm}
          registration={register("password_confirmation")}
          hasError={!!errors.password_confirmation}
          errorMessage={errors.password_confirmation?.message}
          placeholder="أعد إدخال كلمة المرور"
        />
      </div>
    </div>
  );
}

function SignupStepTwoFields({
  register,
  errors,
  documents,
  vehicleCount,
  termsAccepted,
  setValue,
  onOpenTerms,
  onOpenPrivacy,
  profitRate,
}: Readonly<{
  register: UseFormRegister<SignupData>;
  errors: FieldErrors<SignupData>;
  documents: File[];
  vehicleCount: string;
  termsAccepted: boolean;
  setValue: UseFormSetValue<SignupData>;
  onOpenTerms: () => void;
  onOpenPrivacy: () => void;
  profitRate: ProfitRateValue;
}>) {
  return (
    <div key="step-2" className="flex flex-col gap-4">
      <div>
        <label
          htmlFor="signup-national-id"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          رقم الهوية الوطنية
        </label>
        <div className="relative">
          <input
            id="signup-national-id"
            {...register("national_id")}
            placeholder="1XXXXXXXXX"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 pr-12 outline-none transition-colors placeholder-gray-600 ${fieldBorderClass(!!errors.national_id)}`}
            dir="ltr"
          />
          <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center pointer-events-none">
            <i className="ri-id-card-line text-gray-500" />
          </div>
        </div>
        {errors.national_id && (
          <p className="text-red-400 text-xs mt-1.5 text-right">
            {errors.national_id.message}
          </p>
        )}
      </div>

      <div>
        <label
          htmlFor="signup-iban"
          className="text-gray-400 text-xs text-right block mb-2"
        >
          رقم الآيبان البنكي
        </label>
        <div className="relative">
          <input
            id="signup-iban"
            {...register("iban")}
            placeholder="SA00 0000 0000 0000 0000 0000"
            className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-3.5 pr-12 outline-none transition-colors placeholder-gray-600 font-mono ${fieldBorderClass(!!errors.iban)}`}
            dir="ltr"
          />
          <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center pointer-events-none">
            <i className="ri-bank-line text-gray-500" />
          </div>
        </div>
        {errors.iban && (
          <p className="text-red-400 text-xs mt-1.5 text-right">
            {errors.iban.message}
          </p>
        )}
      </div>

      <fieldset>
        <legend className="text-gray-400 text-xs text-right block mb-2 w-full">
          عدد المركبات المراد استثمارها
        </legend>
        <div className="grid grid-cols-4 gap-2">
          {["10+", "6-10", "3-5", "1-2"].map((n) => (
            <button
              key={n}
              type="button"
              onClick={() =>
                setValue("vehicle_count", n, { shouldValidate: true })
              }
              className={`border py-3 text-center text-sm font-semibold rounded-xl cursor-pointer transition-all ${
                vehicleCount === n
                  ? "bg-[#FCD704]/15 border-[#FCD704] text-[#FCD704]"
                  : "bg-[#13151A] border-white/8 text-gray-400 hover:text-white"
              }`}
            >
              {n}
            </button>
          ))}
        </div>
      </fieldset>

      <div>
        <DocumentsUpload
          files={documents}
          onAddFile={(file) =>
            setValue("documents", [...documents, file], {
              shouldValidate: true,
            })
          }
          onRemoveFile={(idx) =>
            setValue(
              "documents",
              documents.filter((_, i) => i !== idx),
              { shouldValidate: true },
            )
          }
        />
        {errors.documents && (
          <p className="text-red-400 text-xs mt-1.5 text-right">
            {errors.documents.message}
          </p>
        )}
      </div>

      <div className="bg-[#FCD704]/8 border border-[#FCD704]/20 rounded-xl p-4 flex items-start gap-3  mt-2">
        <i className="ri-information-line text-[#FCD704] text-lg flex-shrink-0 mt-0.5" />
        <div>
          <p className="text-[#FCD704] text-xs font-bold">
            نسبة الأرباح المتوقعة
          </p>
          <p className="text-gray-400 text-xs mt-0.5">
            {profitRate === null
              ? "سيتم تحديد نسبة أرباحك من النظام"
              : `ستحصل على ${String(profitRate).includes("%") ? profitRate : `${profitRate}%`} من إجمالي إيرادات مركباتك`}
          </p>
        </div>
      </div>

      <div className="flex items-start gap-2  mt-1 select-none">
        <button
          id="terms-check"
          type="button"
          onClick={() =>
            setValue("terms_accepted", !termsAccepted, { shouldValidate: true })
          }
          className={`w-4 h-4 border rounded flex items-center justify-center flex-shrink-0 mt-0.5 cursor-pointer transition-colors ${
            termsAccepted
              ? "bg-[#FCD704]/20 border-[#FCD704]/50"
              : "border-white/20 bg-transparent"
          }`}
        >
          {termsAccepted && (
            <i className="ri-check-line text-[#FCD704] text-xs" />
          )}
        </button>

        <span className="text-gray-400 text-xs text-right leading-relaxed">
          أوافق على{" "}
          <button
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              onOpenTerms();
            }}
            className="text-[#FCD704] hover:underline cursor-pointer"
          >
            الشروط والأحكام
          </button>{" "}
          و{" "}
          <button
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              onOpenPrivacy();
            }}
            className="text-[#FCD704] hover:underline cursor-pointer"
          >
            سياسة الخصوصية
          </button>
        </span>
      </div>
      {errors.terms_accepted && (
        <p className="text-red-400 text-xs mt-1.5 text-right">
          {errors.terms_accepted.message}
        </p>
      )}
    </div>
  );
}

function buildSignupFormData(data: SignupData): FormData {
  const fd = new FormData();
  fd.append("first_name", data.first_name);
  fd.append("last_name", data.last_name);
  fd.append("email", data.email);
  fd.append("phone", data.phone);
  fd.append("country_code", "966");
  fd.append("password", data.password);
  fd.append("password_confirmation", data.password_confirmation);
  fd.append("national_id", data.national_id);
  fd.append("iban", data.iban);
  fd.append("vehicle_count", data.vehicle_count);
  fd.append("terms_accepted", "1");
  data.documents.forEach((file) => {
    fd.append("documents[]", file);
  });
  return fd;
}

export default function SignupForm() {
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuth);
  const { validation } = useValidation();
  const { stats } = useProviderStats();

  const schema = object({
    first_name: validation.name("الرجاء إدخال الاسم الأول"),
    last_name: validation.name("الرجاء إدخال الاسم الأخير"),
    email: validation.email(),
    phone: validation.phone(),
    password: validation.strict_password(),
    password_confirmation: validation.strict_password_confirmation(),
    national_id: validation.national_id(),
    iban: validation.iban(),
    vehicle_count: validation.select_option(),
    documents: validation.files("الرجاء إرفاق المستندات المطلوبة"),
    terms_accepted: validation.checkbox(
      "يجب الموافقة على الشروط والأحكام للمتابعة",
    ),
  });

  const {
    register,
    handleSubmit: rhfSubmit,
    trigger,
    watch,
    setValue,
    formState: { errors },
  } = useForm<SignupData>({
    resolver: yupResolver(schema) as Resolver<SignupData>,
    defaultValues: {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      password: "",
      password_confirmation: "",
      national_id: "",
      iban: "",
      vehicle_count: "6-10",
      documents: [],
      terms_accepted: false,
    },
  });

  const [show, setShow] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [legalModal, setLegalModal] = useState<"terms" | "privacy" | null>(
    null,
  );

  const vehicleCount = watch("vehicle_count");
  const documents = watch("documents");
  const termsAccepted = watch("terms_accepted");

  const handleNextStep = async () => {
    setError("");
    const ok = await trigger([
      "first_name",
      "last_name",
      "email",
      "phone",
      "password",
      "password_confirmation",
    ]);
    if (ok) {
      setStep(2);
    }
  };

  const onValid = async (data: SignupData) => {
    setError("");
    setLoading(true);
    await apiFetch<AuthInfo>("/provider/register", {
      method: "POST",
      getSuccess: true,
      body: buildSignupFormData(data),
      successCase: (res) => {
        if (res.data) setAuth(res.data);
        setStep(3);
      },
      errorCase: (res) => {
        setError(
          formatApiMsg(res.msg) || "حدث خطأ أثناء إنشاء الحساب، حاول مرة أخرى",
        );
      },
      needApproveCase: () => {
        router.push("/login");
      },
      needVerifyCase: (res) => {
        setError(formatApiMsg(res.msg) || "يرجى التحقق من حسابك");
      },
    });
    setLoading(false);
  };

  const handleFormSubmit = (e: SubmitEvent<HTMLFormElement>) => {
    if (step === 1) {
      e.preventDefault();
      handleNextStep();
      return;
    }
    rhfSubmit(onValid)(e);
  };

  if (step === 3) {
    return <SignupSuccessScreen />;
  }

  const activeStep: 1 | 2 = step;

  return (
    <div className="flex flex-col w-full">
      <div className="text-right mb-6">
        <h2 className="text-white font-bold text-[30px] leading-9 mb-2">
          إنشاء حساب جديد ✨
        </h2>
        <p className="text-gray-400 text-sm">
          انضم لمنصة BEEBPEEP وابدأ استثمارك
        </p>
      </div>

      <SignupStepper step={activeStep} />

      <form onSubmit={handleFormSubmit} className="flex flex-col gap-4">
        {activeStep === 1 ? (
          <SignupStepOneFields
            register={register}
            errors={errors}
            show={show}
            showConfirm={showConfirm}
            onToggleShow={() => setShow((value) => !value)}
            onToggleShowConfirm={() => setShowConfirm((value) => !value)}
          />
        ) : (
          <SignupStepTwoFields
            register={register}
            errors={errors}
            documents={documents}
            vehicleCount={vehicleCount}
            termsAccepted={termsAccepted}
            setValue={setValue}
            onOpenTerms={() => setLegalModal("terms")}
            onOpenPrivacy={() => setLegalModal("privacy")}
            profitRate={stats.profit_rate}
          />
        )}

        {error && (
          <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-3 text-center">
            <p className="text-red-400 text-sm">{error}</p>
          </div>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-[#FCD704] text-[#13151A] font-bold text-base py-4 rounded-xl cursor-pointer whitespace-nowrap mt-2 flex items-center justify-center gap-2 hover:bg-[#FCD704]/90 disabled:opacity-70 transition-opacity"
        >
          {loading ? (
            <>
              <i className="ri-loader-4-line animate-spin text-lg" />
              <span>جاري المعالجة...</span>
            </>
          ) : (
            <span>{activeStep === 1 ? "التالي ←" : "إنشاء الحساب"}</span>
          )}
        </button>

        {activeStep === 2 && (
          <button
            type="button"
            onClick={() => {
              setStep(1);
              setError("");
            }}
            className="text-gray-400 text-sm text-center cursor-pointer hover:text-white transition-colors"
          >
            → العودة للخطوة السابقة
          </button>
        )}

        <p className="text-center text-gray-400 text-sm mt-1">
          لديك حساب بالفعل؟{" "}
          <Link
            href="/login"
            className="text-[#FCD704] font-semibold cursor-pointer hover:underline"
          >
            تسجيل الدخول
          </Link>
        </p>
      </form>

      <LegalContentModal
        isOpen={legalModal === "terms"}
        onClose={() => setLegalModal(null)}
        title="الشروط والأحكام"
        endpoint="/terms"
      />
      <LegalContentModal
        isOpen={legalModal === "privacy"}
        onClose={() => setLegalModal(null)}
        title="سياسة الخصوصية"
        endpoint="/privacy"
      />
    </div>
  );
}
