"use client";

import { Autocomplete, AutocompleteItem } from "@heroui/react";
import { Controller, useForm } from "react-hook-form";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useEffect, useState } from "react";
import DynamicInput from "@/components/input";
import DynamicButton from "@/components/button";
import { uploadImage } from "@/actions/upload-image"; // ✅ أكشن الرفع
import { useProfile, useUpdateProfile } from "@/lib/clientQueries";
import { Select, SelectItem } from "@heroui/react";
import { useTranslations } from "next-intl";
import AtayaLoader from "@/components/loaders/AtayaLoader";
import { useAppToast } from "@/app/[lang]/providers";
import { API_BASE_URL } from "@/lib/axios";

type ProfileFormValues = {
  stable_name: string;
  first_name: string;
  last_name: string;
  email: string;
  gender: string;
  country_id: number;
  state_id: number;
  neighborhood: string;
};

export default function ProfileSection() {
  const t = useTranslations("DASHBOARD.PROFILE");
  const toast = useAppToast();
  const { data: profileRaw, isLoading } = useProfile();
  const updateProfile = useUpdateProfile();
  const profile =
    profileRaw && typeof profileRaw === "object" && "data" in profileRaw
      ? (profileRaw as { data: any }).data
      : profileRaw;
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [uploadedUrl, setUploadedUrl] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  const [states, setStates] = useState<any[]>([]);
  const [loadingStates, setLoadingStates] = useState(false);

  const findRiyadh = (list: any[]) => {
    return (list || []).find((s) => {
      const n = String(s?.name || "").toLowerCase();
      return n.includes("الرياض") || n.includes("riyadh");
    });
  };

  const profileSchema: Yup.ObjectSchema<ProfileFormValues> = Yup.object({
    stable_name: Yup.string().required(t("errors.stable_name_required")).min(1),
    first_name: Yup.string().required(t("errors.name_required")).min(1),
    last_name: Yup.string().required(t("errors.name_required")).min(1),
    email: Yup.string()
      .email(t("errors.email_invalid"))
      .required(t("errors.email_required")),
    gender: Yup.string().required(t("errors.gender_required")),
    country_id: Yup.number().required(t("errors.country_required")),
    state_id: Yup.number().required(t("errors.state_required")),
    neighborhood: Yup.string().required(t("errors.neighborhood_required")).min(1),
  }).required();

  const {
    control,
    handleSubmit,
    reset,
    watch,
    setValue,
    formState: { errors },
  } = useForm<ProfileFormValues>({
    resolver: yupResolver<ProfileFormValues, any, ProfileFormValues>(
      profileSchema,
    ),
    defaultValues: {
      stable_name: "",
      first_name: "",
      last_name: "",
      email: "",
      gender: "male",
      country_id: 1,
      state_id: 0,
      neighborhood: "",
    },
  });

  useEffect(() => {
    if (!profile || typeof profile !== "object") return;
    const countryId =
      profile.country?.id != null
        ? Number(profile.country.id)
        : profile.country_id != null
          ? Number(profile.country_id)
          : 0;
    const stateId =
      profile.state?.id != null
        ? Number(profile.state.id)
        : profile.state_id != null
          ? Number(profile.state_id)
          : 0;
    const profileUrl =
      profile.media_files?.profile?.url ??
      (typeof profile.media_files?.profile === "string"
        ? profile.media_files.profile
        : null);
    const firstName =
      profile.first_name ??
      (profile.name ? profile.name.split(/\s+/)[0] || "" : "");
    const lastName =
      profile.last_name ??
      (profile.name && profile.name.split(/\s+/).length > 1
        ? profile.name.split(/\s+/).slice(1).join(" ")
        : "");
    reset({
      stable_name: profile.stable_name ?? "",
      first_name: firstName,
      last_name: lastName,
      email: profile.email ?? "",
      gender: profile.gender ?? "male",
      country_id: countryId || 1,
      state_id: stateId || 0,
      neighborhood: profile.neighborhood ?? "",
    });
    setImagePreview(profileUrl || null);
    setUploadedUrl(profileUrl || null);
  }, [profile, reset]);

  const watchedCountryId = watch("country_id");
  const watchedStateId = watch("state_id");

  useEffect(() => {
    const fetchStates = async () => {
      if (!watchedCountryId) {
        setStates([]);
        return;
      }

      setLoadingStates(true);

      try {
        const res = await fetch(
          `${API_BASE_URL}/user/config/reference-data?states=1&country_id=${watchedCountryId}`,
        );
        const data = await res.json();

        const list = (data?.data?.states as any[]) || data?.data || [];
        const riyadh = findRiyadh(list);
        const nextStates =
          String(watchedCountryId) === "1" && riyadh
            ? [
                riyadh,
                ...list.filter((s: any) => String(s?.id) !== String(riyadh.id)),
              ]
            : list;

        setStates(nextStates);

        if (String(watchedCountryId) === "1" && !watchedStateId && riyadh?.id) {
          setValue("state_id", Number(riyadh.id));
        }
      } catch (err) {
        console.error("Error loading states:", err);
        setStates([]);
      } finally {
        setLoadingStates(false);
      }
    };

    fetchStates();
  }, [watchedCountryId, watchedStateId, setValue]);

  if (isLoading) {
    return <AtayaLoader />;
  }

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    setUploadedUrl(null);
    setImagePreview(URL.createObjectURL(file));

    const formData = new FormData();
    formData.append("model_name", "User");
    formData.append("media[profile]", file);

    try {
      const res = await uploadImage(formData);

      if (res?.success && Array.isArray(res.data) && res.data.length > 0) {
        const fileData = res.data[0];
        setUploadedUrl(fileData.url);
      } else if (res?.data?.url) {
        setUploadedUrl(res.data.url);
      } else {
        toast.error(t("alerts.upload_failed"));
      }
    } catch (error) {
      console.error("رفع الصورة فشل:", error);
      toast.error(t("alerts.upload_error"));
    } finally {
      // إيقاف حالة التحميل حتى تختفي طبقة اللودينغ فوق الصورة
      setIsUploading(false);
    }
  };

  const onSubmit = (data: ProfileFormValues) => {
    if (isUploading) {
      toast.error(t("alerts.wait_upload"));
      return;
    }
    const payload: Record<string, unknown> = {
      stable_name: (data.stable_name || "").trim() || undefined,
      first_name: (data.first_name || "").trim() || undefined,
      last_name: (data.last_name || "").trim() || undefined,
      email: (data.email || "").trim() || undefined,
      gender: (data.gender || "").trim() || undefined,
      state_id: data.state_id,
      neighborhood: (data.neighborhood || "").trim() || undefined,
    };

    if (uploadedUrl) {
      payload.media_files = [
        {
          collection_name: "profile",
          url: uploadedUrl,
        },
      ];
    }

    Object.keys(payload).forEach((k) => {
      if (
        payload[k] === undefined ||
        payload[k] === null ||
        payload[k] === ""
      ) {
        delete payload[k];
      }
    });

    updateProfile.mutate(payload as any, {
      onSuccess: () => {
        toast.success(t("alerts.save_success"));
      },
      onError: () => {
        toast.error(t("alerts.save_error"));
      },
    });
  };

  return (
    <div className="space-y-4">
      <div className="text-start space-y-4">
        <h2 className="text-xl font-extrabold text-primary mb-4">
          {t("title")}
        </h2>

        <div className="flex flex-col items-start gap-3">
          <div className="relative w-28 h-28 rounded-full overflow-hidden border-2 border-gray-300">
            {imagePreview ? (
              <img
                src={imagePreview}
                alt={t("image_alt")}
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="w-full h-full bg-gray-200 flex items-center justify-center text-gray-400">
                {t("no_image")}
              </div>
            )}

            {isUploading && (
              <div className="absolute inset-0 bg-white/60 flex items-center justify-center">
                <AtayaLoader size={48} />
              </div>
            )}
          </div>

          <label className="cursor-pointer bg-gray-200 hover:bg-gray-300 px-4 py-2 rounded-lg text-sm">
            {t("choose_image")}
            <input
              type="file"
              accept="image/*"
              onChange={handleImageUpload}
              className="hidden"
            />
          </label>
        </div>

        {/* 🧾 النموذج */}
        <form
          onSubmit={handleSubmit(onSubmit)}
          className="grid grid-cols-1 sm:grid-cols-3 gap-2"
        >
          <Controller
            name="stable_name"
            control={control}
            render={({ field, fieldState }) => (
              <DynamicInput
                field={field}
                fieldState={fieldState}
                label={t("fields.stable_name_label")}
                placeholder={t("fields.stable_name_placeholder")}
              />
            )}
          />

          <Controller
            name="first_name"
            control={control}
            render={({ field, fieldState }) => (
              <DynamicInput
                field={field}
                fieldState={fieldState}
                label={t("fields.first_name_label")}
                placeholder={t("fields.first_name_placeholder")}
              />
            )}
          />

          <Controller
            name="last_name"
            control={control}
            render={({ field, fieldState }) => (
              <DynamicInput
                field={field}
                fieldState={fieldState}
                label={t("fields.last_name_label")}
                placeholder={t("fields.last_name_placeholder")}
              />
            )}
          />

          <Controller
            name="email"
            control={control}
            render={({ field, fieldState }) => (
              <DynamicInput
                field={field}
                fieldState={fieldState}
                label={t("fields.email_label")}
                placeholder={t("fields.email_placeholder")}
                className="justify-end "
              />
            )}
          />

          <Controller
            name="gender"
            control={control}
            render={({ field, fieldState }) => (
              <div className="flex flex-col gap-1 sm:col-span-1 mt-6">
                <label className="text-sm font-semibold text-gray-700 mb-1">
                  {t("fields.gender_label")}
                </label>
                <Select
                  selectedKeys={field.value ? [String(field.value)] : []}
                  onSelectionChange={(keys) => {
                    const k = Array.from(keys)[0];
                    field.onChange(k ?? "");
                  }}
                  variant="flat"
                  className="max-w-full"
                  isInvalid={!!fieldState.error}
                  errorMessage={
                    fieldState.error ? String(fieldState.error.message) : undefined
                  }
                >
                  <SelectItem key="male">
                    {t("fields.gender_options.male")}
                  </SelectItem>
                  <SelectItem key="female">
                    {t("fields.gender_options.female")}
                  </SelectItem>
                </Select>
              </div>
            )}
          />

          <Controller
            name="country_id"
            control={control}
            render={({ field, fieldState }) => (
              <div className="flex flex-col gap-1 sm:col-span-1 mt-6">
                <label className="text-sm font-semibold text-gray-700 mb-1">
                  {t("fields.country_label")}
                </label>

                <Autocomplete
                  selectedKey={field.value ? String(field.value) : undefined}
                  onSelectionChange={(key) => {
                    if (key) {
                      field.onChange(Number(key));
                      setValue("state_id", 0);
                    }
                  }}
                  placeholder={t("fields.country_placeholder")}
                  variant="flat"
                  className="max-w-full"
                  isDisabled={!profile?.countries?.length}
                  defaultItems={profile?.countries || []}
                  isInvalid={!!fieldState.error}
                  errorMessage={
                    fieldState.error ? String(fieldState.error.message) : undefined
                  }
                >
                  {(country: any) => (
                    <AutocompleteItem key={String(country.id)}>
                      {country.name}
                    </AutocompleteItem>
                  )}
                </Autocomplete>
              </div>
            )}
          />

          <Controller
            name="state_id"
            control={control}
            render={({ field, fieldState }) => (
              <div className="flex flex-col gap-1 sm:col-span-1 mt-6">
                <label className="text-sm font-semibold text-gray-700 mb-1">
                  {t("fields.state_label")}
                </label>

                <Autocomplete
                  selectedKey={field.value ? String(field.value) : undefined}
                  onSelectionChange={(key) => {
                    if (key) {
                      field.onChange(Number(key));
                    }
                  }}
                  placeholder={
                    !watchedCountryId
                      ? t("fields.select_country_first")
                      : loadingStates
                        ? t("fields.loading_states")
                        : t("fields.state_placeholder")
                  }
                  variant="flat"
                  className="max-w-full"
                  isDisabled={!watchedCountryId || loadingStates}
                  isLoading={loadingStates}
                  defaultItems={states}
                  isInvalid={!!fieldState.error}
                  errorMessage={
                    fieldState.error ? String(fieldState.error.message) : undefined
                  }
                >
                  {(state: any) => (
                    <AutocompleteItem key={String(state.id)}>
                      {state.name}
                    </AutocompleteItem>
                  )}
                </Autocomplete>
              </div>
            )}
          />

          <Controller
            name="neighborhood"
            control={control}
            render={({ field, fieldState }) => (
              <DynamicInput
                field={field}
                fieldState={fieldState}
                label={t("fields.neighborhood_label")}
                placeholder={t("fields.neighborhood_placeholder")}
                className="justify-end"
              />
            )}
          />

          <div className="sm:col-span-3 flex gap-3 mt-4 justify-end">
            <DynamicButton
              onClick={handleSubmit(onSubmit)}
              isDisabled={isUploading || updateProfile.isPending}
              isLoading={updateProfile.isPending}
              className={`px-5 py-3 rounded-xl text-white justify-end ${
                isUploading
                  ? "bg-gray-400 cursor-not-allowed"
                  : "bg-primary hover:bg-gray-500"
              }`}
            >
              {t("save_button")}
            </DynamicButton>
          </div>
        </form>
      </div>
    </div>
  );
}
