"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 { ScrollArea } from "@radix-ui/react-scroll-area";
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";

// Zod schema for store settings
const storeSchema = z.object({
  name: z.string(),
  sheba: z.string(),
  bio: z.string().optional(),
  profileImage: z.string().optional(),
  tags: z.array(z.object({ value: z.string() })).optional(),
});

type StoreFormValues = z.infer<typeof storeSchema>;



interface AcademyResponse {
  academy: Academy;
}

//
type TagType = { value: string };

export default function StoreSettings() {
  const { request, loading, error } = useAxios();
  const router = useRouter();
  const { t } = useTranslation("common");
  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: [],
    },
  });

  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 || "");

          // تنظیم مقادیر فرم
          form.reset({
            name: response.academy.academy_name || "",
            bio: response.academy.bio || "",
            profileImage: response.academy.academy_image || "",
            sheba: response.academy.sheba || "",
            tags: tagsArray,
          });

          // تنظیم پیش‌نمایش عکس
          if (response.academy.academy_image) {
            setPreviewProfile(response.academy.academy_image);
            setAvatar(response.academy.academy_image);
          }
        }
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
        toast.error("خطا در دریافت اطلاعات");
      } 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("نام را پر کنید");
      setIsLoading(false);
      return;
    }
    if (!data.sheba) {
      toast.error("شبا را پر کنید");
      setIsLoading(false);
      return;
    }
    if (!data.bio) {
      toast.error("بیو را پر کنید");
      setIsLoading(false);
      return;
    }

    const fileInput = document.getElementById("fileInput") as HTMLInputElement;
    if (!fileInput?.files?.[0]) {
      toast.error("لطفا تصویر پروفایل را انتخاب کنید");
      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 || []));

    try {
      await request("POST", "/academy/academy/profile", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      toast.success("ثبت شد");
      router.push("/settings/academy/Dashboard");
    } catch (err) {
      console.log("Upload error:", err);
      toast.error("خطا در ثبت اطلاعات");
    } finally {
      setIsLoading(false);
    }
  };

  // نمایش لودینگ در حین دریافت دیتا
  if (isFetching) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
      className="w-full p-6 max-w-4xl mx-auto mb-32"
      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">
        {"مشخصات آموزشگاه"}
      </h2>
      <Form {...form}>
        <form
          dir="rtl"
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-8"
        >
          <ScrollArea
            dir="rtl"
            className="max-h-[80vh] p-4 border flex flex-col"
          >
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{"نام آموزشگاه"}</FormLabel>
                    <FormControl>
                      <Input placeholder={"نام آموزشگاه"} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="sheba"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{"شبا"}</FormLabel>
                    <FormControl>
                      <Input placeholder={"شبا"} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <Separator className="mb-3" />
            <FormField
              control={form.control}
              name="bio"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="mt-1.5">{"بیو"}</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder={"درباره فروشگاه خود بنویسید"}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Separator className="mb-3" />
            <FormItem>
              <FormLabel className="mt-1.5">{"عکس پروفایل"}</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">{"تگ های فروشگاه"}</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={"تگ"}
                  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="تگ"]'
                    ) as HTMLInputElement;
                    if (input.value) {
                      appendTag({ value: input.value });
                      input.value = "";
                    }
                  }}
                >
                  {"ثبت"}
                </Button>
              </div>
              <FormMessage />
            </FormItem>
            <Separator className="mb-3" />

            <motion.div
              className="flex justify-center items-center gap-4 w-full"
              whileHover={{ scale: 1.05 }}
              transition={{ duration: 0.2 }}
            >
              <Button
                type="submit"
                disabled={isLoading}
                className="bg-gradient-to-r from-primary w-11/12 to-primary/80"
              >
                {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>
                    "در حال ثبت..."
                  </>
                ) : (
                  "ثبت"
                )}
              </Button>
            </motion.div>
          </ScrollArea>
        </form>
      </Form>
    </motion.div>
  );
}
