"use client";
import { useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useForm, type Resolver } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string } from "yup";
import DashboardLayout from "@/components/DashboardLayout";
import { performLogout } from "@/lib/auth/logout";
import { useValidation } from "@/hooks/useValidation";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { formatProfitRateLabel } from "@/lib/profitRate";

// ── Types ────────────────────────────────────────────────────────────────────

export interface ProfileDashboardPreview {
  rides_today: number;
  profit_rate?: number | string;
  profit_share_percent?: number;
  active_vehicles: number;
}

export interface ProfileData {
  name: string;
  email: string;
  phone: string;
  country_code: string;
  national_id: string; // masked display value e.g. "••••••••90"
  national_id_full: string; // full value for prefilling the edit form
  iban: string; // masked display value
  iban_full: string; // full value for prefilling the edit form
  avatar_initials: string; // e.g. "SA"
  investor_since: string; // e.g. "مستثمر منذ يونيو 2026"
  membership_months: number;
  profit_rate_label: string; // e.g. "18% نسبة الأرباح"
  profit_rate?: number | string;
  vehicle_count: string; // range string e.g. "3-5"
  vehicles_count: number;
  has_pending_profile_update: boolean;
  is_approved: boolean;
  is_verified: boolean;
  dashboard_preview: ProfileDashboardPreview;
}

// Editable form fields sent to provider/update/profile.
interface ProfileEditForm {
  name: string;
  country_code: string;
  phone: string;
  national_id: string;
  iban: string;
}

// ── Skeleton ─────────────────────────────────────────────────────────────────

const PROFILE_STAT_SKELETON_KEYS = [
  "profile-stat-skeleton-1",
  "profile-stat-skeleton-2",
  "profile-stat-skeleton-3",
] as const;

const PROFILE_FIELD_SKELETON_KEYS = [
  { key: "profile-field-skeleton-1", fullWidth: false },
  { key: "profile-field-skeleton-2", fullWidth: false },
  { key: "profile-field-skeleton-3", fullWidth: false },
  { key: "profile-field-skeleton-4", fullWidth: false },
  { key: "profile-field-skeleton-5", fullWidth: true },
] as const;

function ProfileSkeleton() {
  return (
    <div className="grid grid-cols-3 gap-6">
      {/* Left col skeleton */}
      <div className="flex flex-col gap-5">
        <div className="bg-[#1E2128] rounded-2xl p-6 flex flex-col items-center animate-pulse">
          <div className="w-24 h-24 bg-white/5 rounded-full mb-4" />
          <div className="h-5 w-32 bg-white/10 rounded mb-2" />
          <div className="h-3 w-24 bg-white/5 rounded mb-3" />
          <div className="h-6 w-28 bg-white/5 rounded-full" />
        </div>
        <div className="grid grid-cols-1 gap-3">
          {PROFILE_STAT_SKELETON_KEYS.map((skeletonKey) => (
            <div key={skeletonKey} className="bg-[#1E2128] rounded-xl p-4 flex items-center justify-between animate-pulse">
              <div className="h-3 w-20 bg-white/5 rounded" />
              <div className="h-5 w-12 bg-white/10 rounded" />
            </div>
          ))}
        </div>
      </div>
      {/* Right col skeleton */}
      <div className="col-span-2 bg-[#1E2128] rounded-2xl p-6 animate-pulse">
        <div className="h-5 w-32 bg-white/10 rounded mb-6 self-end" />
        <div className="grid grid-cols-2 gap-4">
          {PROFILE_FIELD_SKELETON_KEYS.map(({ key, fullWidth }) => (
            <div key={key} className={fullWidth ? "col-span-2" : ""}>
              <div className="h-3 w-24 bg-white/5 rounded mb-2" />
              <div className="h-12 bg-white/5 rounded-xl" />
            </div>
          ))}
        </div>
        <div className="h-12 bg-white/5 rounded-xl mt-6" />
      </div>
    </div>
  );
}

function renderSubmitButtonContent(
  submitLoading: boolean,
  hasPending: boolean,
): ReactNode {
  if (submitLoading) {
    return (
      <>
        <i className="ri-loader-4-line animate-spin text-lg" />
        <span>جاري الحفظ...</span>
      </>
    );
  }

  if (hasPending) {
    return (
      <>
        <i className="ri-time-line text-lg" />
        <span>في انتظار الموافقة</span>
      </>
    );
  }

  return <span>حفظ التغييرات</span>;
}

// ── Page ─────────────────────────────────────────────────────────────────────

export default function ProfilePage() {
  const router = useRouter();

  // ── Load state ──────────────────────────────────────────────────────────
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [loadLoading, setLoadLoading] = useState(true);
  const [loadError, setLoadError] = useState("");

  // ── Submit state ────────────────────────────────────────────────────────
  const [submitLoading, setSubmitLoading] = useState(false);
  const [submitError, setSubmitError] = useState("");
  // pending = true when there's already a pending update (from load) OR after
  // a successful submit (approval required, data not yet applied).
  const [pendingMsg, setPendingMsg] = useState("");

  // ── Validation + form ───────────────────────────────────────────────────
  const { validation } = useValidation();
  const schema = object({
    name: validation.name(),
    country_code: string().required("رمز الدولة مطلوب"),
    phone: validation.phone({ length: 9 }),
    national_id: validation.national_id(),
    iban: validation.iban(),
  });

  const {
    register,
    handleSubmit: rhfSubmit,
    formState: { errors },
    reset,
  } = useForm<ProfileEditForm>({
    resolver: yupResolver(schema) as Resolver<ProfileEditForm>,
    defaultValues: {
      name: "",
      country_code: "",
      phone: "",
      national_id: "",
      iban: "",
    },
  });

  // ── Logout ──────────────────────────────────────────────────────────────
  const handleLogout = () => {
    void performLogout((loginPath) => router.replace(loginPath));
  };

  // ── Fetch: provider/profile (GET) ───────────────────────────────────────
  useEffect(() => {
    let active = true;
    setLoadLoading(true);
    setLoadError("");
    apiFetch<ProfileData>("/provider/profile", {
      method: "GET",
      successCase: (res) => {
        if (!active || !res.data) return;
        setProfile(res.data);
        // Prefill the edit form with full (unmasked) values.
        reset({
          name: res.data.name,
          country_code: res.data.country_code,
          phone: res.data.phone,
          national_id: res.data.national_id_full,
          iban: res.data.iban_full,
        });
        // If there's already a pending update, show the banner immediately.
        if (res.data.has_pending_profile_update) {
          setPendingMsg(
            "طلب تحديث سابق لا يزال في انتظار موافقة الإدارة — لا يمكن إرسال طلب آخر حالياً",
          );
        }
      },
      errorCase: (res) => {
        if (active)
          setLoadError(
            formatApiMsg(res.msg) ||
              "تعذّر تحميل بيانات الملف الشخصي، حاول مرة أخرى",
          );
      },
    }).finally(() => {
      if (active) setLoadLoading(false);
    });
    return () => {
      active = false;
    };
  }, [reset]);

  // ── Submit: provider/update/profile (POST) ──────────────────────────────
  const onSubmit = async (data: ProfileEditForm) => {
    setSubmitError("");
    setSubmitLoading(true);
    await apiFetch("/provider/update/profile", {
      method: "POST",
      body: JSON.stringify({
        name: data.name,
        country_code: data.country_code,
        phone: data.phone,
        national_id: data.national_id,
        iban: data.iban,
      }),
      successCase: (res) => {
        // Update requires admin approval — do NOT apply values to profile state.
        // Do NOT touch useAuthStore.
        const msg =
          formatApiMsg(res.msg) ||
          "تم إرسال طلب التحديث، في انتظار موافقة الإدارة";
        setPendingMsg(msg);
      },
      needApproveCase: (res) => {
        const msg =
          formatApiMsg(res.msg) ||
          "تم إرسال طلب التحديث، في انتظار موافقة الإدارة";
        setPendingMsg(msg);
      },
      errorCase: (res) => {
        setSubmitError(
          formatApiMsg(res.msg) || "تعذّر حفظ التغييرات، حاول مرة أخرى",
        );
      },
    });
    setSubmitLoading(false);
  };

  // ── Derived ─────────────────────────────────────────────────────────────
  const hasPending = Boolean(pendingMsg);

  // ── Render ───────────────────────────────────────────────────────────────
  if (loadLoading) {
    return (
      <DashboardLayout
        title="الملف الشخصي"
        subtitle="إدارة معلوماتك الشخصية وإعدادات حسابك"
      >
        <ProfileSkeleton />
      </DashboardLayout>
    );
  }

  if (loadError) {
    return (
      <DashboardLayout
        title="الملف الشخصي"
        subtitle="إدارة معلوماتك الشخصية وإعدادات حسابك"
      >
        <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-8 text-center">
          <i className="ri-error-warning-line text-red-400 text-3xl mb-3 block" />
          <p className="text-red-400 text-sm">{loadError}</p>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout
      title="الملف الشخصي"
      subtitle="إدارة معلوماتك الشخصية وإعدادات حسابك"
    >
      <div className="grid grid-cols-3 gap-6">
        {/* ── Left column ─────────────────────────────────────────────── */}
        <div className="flex flex-col gap-5">
          {/* Avatar + identity card */}
          <div className="bg-[#1E2128] rounded-2xl p-6 flex flex-col items-center text-center">
            {/* Initials avatar — image ignored per spec */}
            <div className="w-24 h-24 bg-[#13151A] rounded-full flex items-center justify-center border-2 border-[#FCD704]/40">
              <span className="text-white font-bold text-3xl">
                {profile?.avatar_initials ?? "؟"}
              </span>
            </div>
            <h2 className="text-white font-bold text-xl mt-4">
              {profile?.name}
            </h2>
            <p className="text-gray-400 text-xs mt-1">
              {profile?.investor_since}
            </p>
            {/* Verified / approved badges */}
            {profile?.is_verified && (
              <span className="mt-3 bg-[#FCD704]/20 text-[#FCD704] text-xs font-semibold px-3 py-1.5 rounded-full">
                حساب موثّق ✓
              </span>
            )}
            {!profile?.is_approved && (
              <span className="mt-2 bg-orange-400/20 text-orange-400 text-xs font-semibold px-3 py-1.5 rounded-full">
                في انتظار الموافقة
              </span>
            )}
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 gap-3">
            {[
              {
                val: String(profile?.vehicles_count ?? "—"),
                label: "مركبات",
              },
              {
                val: profile?.profit_rate_label ?? "—",
                label: "نسبة الأرباح",
              },
              {
                val:
                  profile?.membership_months == null
                    ? "—"
                    : `${profile.membership_months} شهر`,
                label: "عضوية نشطة",
              },
            ].map((s) => (
              <div
                key={s.label}
                className="bg-[#1E2128] rounded-xl p-4 flex items-center justify-between"
              >
                <span className="text-gray-400 text-sm">{s.label}</span>
                <span className="text-white font-black text-xl">{s.val}</span>
              </div>
            ))}
          </div>

          {/* Dashboard preview */}
          {profile?.dashboard_preview && (
            <div className="bg-[#1E2128] rounded-xl p-4 flex flex-col gap-2">
              <h4 className="text-gray-400 text-xs text-right mb-1">
                نشاط اليوم
              </h4>
              {[
                {
                  label: "رحلات اليوم",
                  val: String(profile.dashboard_preview.rides_today),
                },
                {
                  label: "المركبات النشطة",
                  val: String(profile.dashboard_preview.active_vehicles),
                },
                {
                  label: "نسبة الأرباح",
                  val: formatProfitRateLabel(
                    profile.profit_rate_label,
                    profile.profit_rate ??
                      profile.dashboard_preview.profit_rate ??
                      profile.dashboard_preview.profit_share_percent,
                  ),
                },
              ].map((item) => (
                <div key={item.label} className="flex items-center justify-between">
                  <span className="text-white text-sm font-semibold">
                    {item.val}
                  </span>
                  <span className="text-gray-500 text-xs">{item.label}</span>
                </div>
              ))}
            </div>
          )}

          {/* Actions */}
          <div className="bg-[#1E2128] rounded-2xl p-5 flex flex-col gap-3">
            <h3 className="text-white font-bold text-right text-sm mb-1">
              الإجراءات
            </h3>
            <Link
              href="/change-password"
              className="w-full border border-white/20 text-white font-semibold py-3 rounded-xl cursor-pointer whitespace-nowrap text-sm flex items-center justify-center"
            >
              تغيير كلمة المرور
            </Link>
            <button
              onClick={handleLogout}
              className="text-red-400 text-sm font-semibold cursor-pointer py-2 whitespace-nowrap"
            >
              تسجيل الخروج
            </button>
          </div>
        </div>

        {/* ── Right column: edit form ──────────────────────────────────── */}
        <div className="col-span-2">
          <div className="bg-[#1E2128] rounded-2xl p-6">
            <h3 className="text-white font-bold text-right mb-6">
              المعلومات الشخصية
            </h3>

            {/* Pending-approval banner — shown on load (existing pending) or
                after a successful submit (new pending request sent). */}
            {hasPending && (
              <div className="mb-5 bg-[#FCD704]/10 border border-[#FCD704]/30 rounded-xl p-4 flex items-start gap-3">
                <i className="ri-time-line text-[#FCD704] text-lg flex-shrink-0 mt-0.5" />
                <p className="text-[#FCD704] text-sm text-right flex-1">
                  {pendingMsg}
                </p>
              </div>
            )}

            <form onSubmit={rhfSubmit(onSubmit)}>
              <div className="grid grid-cols-2 gap-4">
                {/* Name */}
                <div>
                  <p className="text-gray-400 text-xs text-right mb-2">
                    الاسم الكامل
                  </p>
                  <div
                    className={`bg-[#13151A] border rounded-xl flex items-center px-4 py-3.5 gap-2 ${errors.name ? "border-red-500/60" : "border-transparent focus-within:border-[#FCD704]/30"}`}
                  >
                    <input
                      {...register("name")}
                      className="flex-1 bg-transparent text-white text-sm outline-none text-right"
                      dir="rtl"
                      placeholder="الاسم الكامل"
                    />
                  </div>
                  {errors.name && (
                    <p className="text-red-400 text-xs mt-1.5 text-right">
                      {errors.name.message}
                    </p>
                  )}
                </div>

                {/* Phone + country_code */}
                <div>
                  <p className="text-gray-400 text-xs text-right mb-2">
                    رقم الجوال
                  </p>
                  <div
                    className={`bg-[#13151A] border rounded-xl flex items-center gap-2 ${errors.phone || errors.country_code ? "border-red-500/60" : "border-transparent focus-within:border-[#FCD704]/30"}`}
                  >
                    {/* Country code — LTR numeric input */}
                    <input
                      {...register("country_code")}
                      className="w-14 bg-transparent text-white text-sm outline-none text-center py-3.5 border-l border-white/10 flex-shrink-0"
                      dir="ltr"
                      placeholder="+966"
                    />
                    {/* Phone digits — LTR numeric */}
                    <input
                      {...register("phone")}
                      className="flex-1 bg-transparent text-white text-sm outline-none py-3.5 px-2"
                      dir="ltr"
                      type="tel"
                      placeholder="5XXXXXXXX"
                    />
                  </div>
                  {(errors.phone || errors.country_code) && (
                    <p className="text-red-400 text-xs mt-1.5 text-right">
                      {errors.phone?.message ?? errors.country_code?.message}
                    </p>
                  )}
                </div>

                {/* Email — read-only, not editable per spec */}
                <div>
                  <p className="text-gray-400 text-xs text-right mb-2">
                    البريد الإلكتروني
                  </p>
                  <div className="bg-[#13151A] border border-transparent rounded-xl flex items-center px-4 py-3.5 gap-2 opacity-60">
                    <i className="ri-lock-2-line text-gray-500 text-sm flex-shrink-0" />
                    <span className="flex-1 text-gray-400 text-sm text-right">
                      {profile?.email}
                    </span>
                  </div>
                </div>

                {/* National ID — full value prefilled, LTR input */}
                <div>
                  <p className="text-gray-400 text-xs text-right mb-2">
                    رقم الهوية الوطنية
                  </p>
                  <div
                    className={`bg-[#13151A] border rounded-xl flex items-center px-4 py-3.5 gap-2 ${errors.national_id ? "border-red-500/60" : "border-transparent focus-within:border-[#FCD704]/30"}`}
                  >
                    <input
                      {...register("national_id")}
                      className="flex-1 bg-transparent text-white text-sm outline-none"
                      dir="ltr"
                      placeholder="1XXXXXXXXX"
                    />
                  </div>
                  {errors.national_id && (
                    <p className="text-red-400 text-xs mt-1.5 text-right">
                      {errors.national_id.message}
                    </p>
                  )}
                </div>

                {/* IBAN — full value prefilled, spans 2 cols, LTR input */}
                <div className="col-span-2">
                  <p className="text-gray-400 text-xs text-right mb-2">
                    رقم الآيبان البنكي
                  </p>
                  <div
                    className={`bg-[#13151A] border rounded-xl flex items-center px-4 py-3.5 gap-2 ${errors.iban ? "border-red-500/60" : "border-transparent focus-within:border-[#FCD704]/30"}`}
                  >
                    <input
                      {...register("iban")}
                      className="flex-1 bg-transparent text-white text-sm outline-none"
                      dir="ltr"
                      placeholder="SA00 0000 0000 0000 0000 0000"
                    />
                  </div>
                  {errors.iban && (
                    <p className="text-red-400 text-xs mt-1.5 text-right">
                      {errors.iban.message}
                    </p>
                  )}
                </div>
              </div>

              {/* Submit error */}
              {submitError && (
                <div className="mt-5 bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-center">
                  <p className="text-red-400 text-sm">{submitError}</p>
                </div>
              )}

              {/* Submit button — disabled while pending or submitting */}
              <button
                type="submit"
                disabled={submitLoading || hasPending}
                className="w-full mt-6 bg-[#FCD704] text-[#13151A] font-bold text-base py-4 rounded-xl cursor-pointer whitespace-nowrap transition-all hover:bg-[#FCD704]/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {renderSubmitButtonContent(submitLoading, hasPending)}
              </button>
            </form>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}
