"use client";

import * as React from "react";
import { useState, useEffect } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { motion } from "framer-motion";
import { toast } from "react-hot-toast";
import { useTranslation } from "react-i18next";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/Textarea";

import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import "leaflet/dist/leaflet.css";
import { useRouter } from "next/navigation";
import useAxios from "@/hooks/useAxios";
import { Academy } from "@/types/types";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import { AcademyProfileHeadSkeleton } from "@/components/academy/AcademySkeletons";
import { Skeleton } from "@/components/ui/skeleton";
import {
  getIranBankName,
  isValidIranSheba,
  stripShebaPrefix,
} from "@/lib/iranSheba";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
import { btnPrimary } from "@/lib/ui/buttonStyles";

function buildStoreSchema(t: (key: string) => string) {
  return z.object({
    name: z.string(),
    sheba: z
      .string()
      .regex(/^\d{24}$/, t("settings.academy.storeProfile.shebaInvalid")),
    bio: z.string().optional(),
    profileImage: z.string().optional(),
    tags: z.array(z.object({ value: z.string() })).optional(),
    contact_mobile: z.string().optional(),
    contact_telegram: z.string().optional(),
    contact_whatsapp: z.string().optional(),
    contact_instagram: z.string().optional(),
  });
}

type StoreFormValues = z.infer<ReturnType<typeof buildStoreSchema>>;



interface AcademyResponse {
  academy: Academy & {
    contactInfo?: {
      mobile?: string;
      phone?: string;
      telegramLink?: string;
      whatsappNumber?: string;
      instagramLink?: string;
    };
  };
}

//
type TagType = { value: string };

export default function StoreSettings() {
  const { request, loading, error } = useAxios();
  const router = useRouter();
  const { t } = useTranslation("common");
  const storeSchema = useMemo(() => buildStoreSchema(t), [t]);
  const tagPlaceholder = t("settings.academy.storeProfile.tagPlaceholder");
  const [previewProfile, setPreviewProfile] = useState<string>("");
  const [avatar, setAvatar] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isFetching, setIsFetching] = useState(true); // برای نمایش لودینگ اولیه

  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const form = useForm<StoreFormValues>({
    resolver: zodResolver(storeSchema),
    defaultValues: {
      name: "",
      bio: "",
      profileImage: "",
      sheba: "",
      tags: [],
      contact_mobile: "",
      contact_telegram: "",
      contact_whatsapp: "",
      contact_instagram: "",
    },
  });

  const shebaValue = form.watch("sheba");
  const shebaValid = isValidIranSheba(shebaValue || "");
  const bankName = shebaValid ? getIranBankName(shebaValue || "") : null;

  const parseTags = (jsonString: string): TagType[] => {
    try {
      const parsed = JSON.parse(jsonString);
      if (Array.isArray(parsed)) {
        const validTags = parsed.filter(
          (item) =>
            item && typeof item === "object" && typeof item.value === "string"
        );
        return validTags as TagType[];
      }
      return [];
    } catch (error) {
      console.error("خطا در parse تگ‌ها:", error);
      return [];
    }
  };

  // دریافت دیتا از سرور
  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsFetching(true);
        const response = (await request("GET", `/academy`)) as AcademyResponse;

        if (response?.academy) {
          const tagsArray = parseTags(response.academy.tag || "");
          const contact = response.academy.contactInfo;

          // تنظیم مقادیر فرم
          form.reset({
            name: response.academy.academy_name || "",
            bio: response.academy.bio || "",
            profileImage: response.academy.academy_image || "",
            sheba: stripShebaPrefix(response.academy.sheba || ""),
            tags: tagsArray,
            contact_mobile: contact?.mobile || contact?.phone || "",
            contact_telegram: contact?.telegramLink || "",
            contact_whatsapp: contact?.whatsappNumber || "",
            contact_instagram: contact?.instagramLink || "",
          });

          // تنظیم پیش‌نمایش عکس
          if (response.academy.academy_image) {
            setPreviewProfile(response.academy.academy_image);
            setAvatar(response.academy.academy_image);
          }
        }
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
        toast.error(t("settings.academy.storeProfile.fetchError"));
      } finally {
        setIsFetching(false);
      }
    };

    fetchData();
  }, []);

  const {
    fields: tagFields,
    append: appendTag,
    remove: removeTag,
  } = useFieldArray({
    control: form.control,
    name: "tags",
  });

  const selectImage = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const previewUrl = URL.createObjectURL(file);
      setPreviewProfile(previewUrl);
      setAvatar(previewUrl);
    }
  };

  const onSubmit = async (data: StoreFormValues) => {
    setIsLoading(true);

    if (!data.name) {
      toast.error(t("settings.academy.storeProfile.nameRequired"));
      setIsLoading(false);
      return;
    }
    if (!data.sheba || !isValidIranSheba(data.sheba)) {
      toast.error(t("settings.academy.storeProfile.shebaRequired"));
      setIsLoading(false);
      return;
    }
    if (!data.bio) {
      toast.error(t("settings.academy.storeProfile.bioRequired"));
      setIsLoading(false);
      return;
    }

    const fileInput = document.getElementById("fileInput") as HTMLInputElement;
    if (!fileInput?.files?.[0]) {
      toast.error(t("settings.academy.storeProfile.imageRequired"));
      setIsLoading(false);
      return;
    }

    const formData = new FormData();
    formData.append("profile_image", fileInput.files[0]);
    formData.append("mobile", mobile as string);
    formData.append("name", data.name);
    formData.append("sheba", data.sheba);
    formData.append("bio", data.bio);
    formData.append("tag", JSON.stringify(data.tags || []));
    formData.append("contact_mobile", data.contact_mobile || "");
    formData.append("contact_telegram", data.contact_telegram || "");
    formData.append("contact_whatsapp", data.contact_whatsapp || "");
    formData.append("contact_instagram", data.contact_instagram || "");

    try {
      await request("POST", "/academy/academy/profile", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      toast.success(t("settings.academy.storeProfile.saved"));
      router.push("/settings/academy/Dashboard");
    } catch (err) {
      console.log("Upload error:", err);
      toast.error(t("settings.academy.storeProfile.saveError"));
    } finally {
      setIsLoading(false);
    }
  };

  // نمایش لودینگ در حین دریافت دیتا
  if (isFetching) {
    return (
      <div className="w-full max-w-4xl mx-auto mb-32 px-4 py-6 lg:px-6">
        <AcademyProfileHeadSkeleton />
        <div className="space-y-4 mt-6">
          <Skeleton className="h-10 w-full" />
          <Skeleton className="h-10 w-full" />
          <Skeleton className="h-32 w-full" />
        </div>
      </div>
    );
  }

  return (
    <LocalePageShell>
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
      className="w-full max-w-4xl mx-auto px-4 pt-6 lg:px-6 pb-[calc(6rem+env(safe-area-inset-bottom))]"
      dir={t("dir") || "rtl"}
    >
      <h2 className="text-3xl font-bold bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent mb-6">
        {t("settings.academy.storeProfile.title")}
      </h2>
      <Form {...form}>
        <form
          dir="rtl"
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-8"
        >
          <div dir="rtl" className="flex flex-col border p-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("settings.academy.storeProfile.name")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("settings.academy.storeProfile.name")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="sheba"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("settings.academy.storeProfile.sheba")}</FormLabel>
                    <div className="flex flex-col gap-1.5">
                      <div className="flex items-center gap-2">
                        <FormControl>
                          <div className="relative flex-1">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-muted-foreground">
                              IR
                            </span>
                            <Input
                              placeholder={t("settings.academy.storeProfile.shebaPlaceholder")}
                              maxLength={24}
                              inputMode="numeric"
                              className={cn(
                                "pl-10 dir-ltr",
                                shebaValid &&
                                  "border-green-500 focus-visible:ring-green-500"
                              )}
                              {...field}
                              onChange={(e) => {
                                const digits = e.target.value
                                  .replace(/\D/g, "")
                                  .slice(0, 24);
                                field.onChange(digits);
                              }}
                            />
                          </div>
                        </FormControl>
                        {bankName ? (
                          <span className="shrink-0 text-xs font-semibold text-green-600 dark:text-green-400">
                            {bankName}
                          </span>
                        ) : null}
                      </div>
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <Separator className="mb-3" />
            <FormField
              control={form.control}
              name="bio"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="mt-1.5">{t("settings.academy.storeProfile.bio")}</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder={t("settings.academy.storeProfile.bioPlaceholder")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Separator className="mb-3" />

            <div className="space-y-3 rounded-xl border border-border-primary-light p-4">
              <FormLabel className="text-base">{t("settings.academy.storeProfile.contactOptional")}</FormLabel>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="contact_mobile"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input placeholder={t("settings.billboards.mobile")} maxLength={11} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_telegram"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input placeholder={t("settings.billboards.telegram")} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_whatsapp"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input placeholder={t("settings.billboards.whatsapp")} maxLength={11} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_instagram"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input placeholder={t("settings.billboards.instagram")} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <Separator className="mb-3" />
            <FormItem>
              <FormLabel className="mt-1.5">{t("settings.academy.storeProfile.profileImage")}</FormLabel>
              <FormControl>
                <Input
                  id="fileInput"
                  type="file"
                  accept="image/*"
                  onChange={selectImage}
                />
              </FormControl>
              {previewProfile && (
                <motion.img
                  src={IMAGE_BASE_URL + previewProfile}
                  alt="Profile Preview"
                  className="w-24 h-24 rounded-xl object-cover mt-2"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                />
              )}
              <FormMessage />
            </FormItem>
            <Separator className="mb-3" />
            <FormItem>
              <FormLabel className="mt-1.5">{t("settings.academy.storeProfile.storeTags")}</FormLabel>
              <div className="flex flex-wrap gap-2 mb-2">
                {tagFields.map((tag, index) => (
                  <Badge key={tag.id}>
                    {tag.value}
                    <Button type="button" onClick={() => removeTag(index)}>
                      X
                    </Button>
                  </Badge>
                ))}
              </div>
              <div className="flex gap-2 mb-2">
                <Input
                  placeholder={tagPlaceholder}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && e.currentTarget.value) {
                      appendTag({ value: e.currentTarget.value });
                      e.currentTarget.value = "";
                    }
                  }}
                />
                <Button
                  type="button"
                  onClick={() => {
                    const input = document.querySelector(
                      `input[placeholder="${tagPlaceholder}"]`
                    ) as HTMLInputElement;
                    if (input.value) {
                      appendTag({ value: input.value });
                      input.value = "";
                    }
                  }}
                >
                  {t("settings.academy.storeProfile.submit")}
                </Button>
              </div>
              <FormMessage />
            </FormItem>
            <Separator className="mb-3" />

            <div className="flex w-full justify-center pt-4">
              <Button
                type="submit"
                disabled={isLoading}
                className={cn(btnPrimary, "h-10 w-11/12")}
              >
                {isLoading ? (
                  <>
                    <svg
                      className="animate-spin h-5 w-5 ml-2"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                        fill="none"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      />
                    </svg>
                    {t("settings.academy.storeProfile.submitting")}
                  </>
                ) : (
                  t("settings.academy.storeProfile.submit")
                )}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </motion.div>
    </LocalePageShell>
  );
}
