"use client";
import React, { useEffect, useRef, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { useRouter } from "next/navigation";
import { EllipsisVertical, Pencil, Trash2 } from "lucide-react";
import Profiles from "@/assets/images/profileimg.png";
import { useGlobalContext } from "@/context/Provider";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import CountryPickerModal from "@/components/countrycode/page";
import countries from "@/utils/CountryCode.json";
import { Modal } from "@/components/ui/modal";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { Input } from "@/components/ui/input";
import { formatDateStringToUTC, formatUTCToDateString } from "@/lib/utils";
import { Button } from "@/components/ui/button";

const Profile = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    dob: "",
    anniversary_date: "",
    gender: "",
  });
  const router = useRouter();
  const [showReport, setShowReport] = useState(false);
  const [valued, setValue] = useState<any>(countries?.[97]);
  const [verify, setVerify] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { Toast, userInfo, getProfile } = useGlobalContext();
  const [image, setImage] = useState('')
  const [loading, setLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [isOpen1, setIsOpen1] = useState(false);
  const [otp, setOtp] = useState("");
  const [otp1, setOtp1] = useState("");

  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };
  useEffect(() => {
    if (userInfo && !verify) {
      setFormData({
        name: userInfo?.name || "",
        email: userInfo?.email || "",
        phone: userInfo?.phone || "",
        dob: userInfo?.dob
          ? formatUTCToDateString(userInfo.dob)
          : "",
        anniversary_date: userInfo?.anniversary_date
          ? formatUTCToDateString(userInfo.anniversary_date)
          : "",
        gender: userInfo?.gender || ""
      });
      setImage(userInfo?.image || "")
      const matchedCountry = countries.find(
        (c: any) =>
          c.dial_code === userInfo.country_code ||
          "+" + c.dial_code === userInfo.country_code
      );
      if (matchedCountry) {
        setValue(matchedCountry);
      }
    }
  }, [userInfo, verify]);

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    if (loading) {
      Toast.error("Please wait while image is uploading...");
      return;
    }
    const minLength = valued?.min_length || 6;
    const maxLength = valued?.max_length || 15;
    const phoneLength = formData.phone?.length || 0;

    if (phoneLength < minLength) {
      Toast.error(`Phone number must be at least ${minLength} digits for ${valued?.name || 'this country'}!`);
      return;
    }

    if (phoneLength > maxLength) {
      Toast.error(`Phone number must not exceed ${maxLength} digits for ${valued?.name || 'this country'}!`);
      return;
    }
    if (formData.name?.length > 55) {
      Toast.error("Name must not exceed 55 characters!");
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!formData.email || !emailRegex.test(formData.email)) {
      Toast.error("Enter a valid email!");
      return;
    }

    if (formData.dob && new Date(formData.dob) > new Date()) {
      Toast.error("Date of Birth cannot be in the future!");
      return;
    }

    if (formData.anniversary_date && new Date(formData.anniversary_date) > new Date()) {
      Toast.error("Anniversary Date cannot be in the future!");
      return;
    }

    let payload: any = {};

    if (formData.dob && formData.dob !== formatUTCToDateString(userInfo?.dob || "")) {
      payload.dob = formatDateStringToUTC(formData.dob);
    }

    if (formData.anniversary_date && formData.anniversary_date !== formatUTCToDateString(userInfo?.anniversary_date || "")) {
      payload.anniversary_date = formatDateStringToUTC(formData.anniversary_date);
    }

    if (image !== userInfo?.image) {
      payload.image = image;
    }

    if (formData.name !== userInfo?.name) {
      payload.name = formData.name;
    }

    if (formData.email !== userInfo?.email) {
      payload.email = formData.email;
    }
    if (formData.phone !== userInfo?.phone) {
      payload.phone = formData.phone;
      payload.country_code = valued?.dial_code;
    }

    if ("+" + valued?.dial_code !== userInfo?.country_code) {
      payload.phone = formData.phone;
      payload.country_code = valued?.dial_code;
    }


    if (formData.gender !== userInfo?.gender) {
      payload.gender = formData.gender;
    }

    try {
      const apiRes = await apis.Profile.UpdateProfile(payload);

      if (
        userInfo?.email !== formData?.email ||
        userInfo?.phone !== formData?.phone ||
        userInfo?.country_code !== "+" + valued?.dial_code
      ) {
        setVerify(true);
        Toast.success("Profile updated! Please verify your new contact details.");
      } else {
        Toast.success("Profile updated successfully!");
        router.push("/home");
      }
    } catch (error) {
      Toast.error("Failed to update profile.");
    }
  };


  const verifyPhone = async (e: any) => {
    let payload: any = {
      otp: otp,
    };
    try {
      const apiRes = await apis.Auth.phoneVerified(payload);
      if (apiRes) {
        setIsOpen(false);
        Toast.success("Phone verified successfully!");
        const updatedUser = await getProfile();
        const currentUser = updatedUser || userInfo;
        const isEmailDifferent = currentUser?.email !== formData?.email;
        if (!isEmailDifferent) {
          setVerify(false);
          router.push("/home");
        }
      }
    } catch (error: any) {
      Toast.error(error);
    }
  };
  const verifyEmail = async (e: any) => {
    let payload: any = {
      otp: otp1,
    };
    try {
      const apiRes = await apis.Auth.emailVerified(payload);
      if (apiRes) {
        setIsOpen1(false);
        Toast.success("Email verified successfully!");
        const updatedUser = await getProfile();
        const currentUser = updatedUser || userInfo;
        const isPhoneDifferent =
          currentUser?.phone !== formData?.phone ||
          currentUser?.country_code !== "+" + valued?.dial_code;
        if (!isPhoneDifferent) {
          setVerify(false);
          router.push("/home");
        }
      }
    } catch (error: any) {
      Toast.error(error);
    }
  };
  const handleFileSelect = () => {
    if (fileInputRef?.current) {
      fileInputRef.current.click();
    }
  };
  const handleUploadImage = async (file: File) => {
    try {
      setLoading(true);
      const apiRes = await apis.Common.uploadFile("file", file);
      setImage(apiRes?.key);
      Toast.success("Image uploaded successfully!");
    } catch (error) {
      Toast.error("Failed to upload image.");
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024;
      const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];

      if (!allowedTypes.includes(file.type)) {
        Toast.error("Only JPG and PNG images are allowed.");
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error("Image size cannot be more than 5MB.");
        return;
      }
      handleUploadImage(file);
    }
  };
  return (
    <div className="w-full flex flex-col items-center mb-20">
      <div
        className="relative w-full max-w-4xl h-[200px] rounded-lg flex flex-col justify-between mb-24 px-0"
      >
        {/* Background container that clips the decorative circles */}
        <div className="absolute inset-0 bg-primary rounded-lg overflow-hidden pointer-events-none z-0">
          {/* Premium Brand Accent Shapes */}
          <div className="absolute -bottom-12 -left-12 w-44 h-44 rounded-full bg-white/10" />
          <div className="absolute -top-12 -right-12 w-44 h-44 rounded-full bg-white/10" />
        </div>

        <div className="w-full flex justify-end relative z-10">
          <div
            className="w-8 h-8 mt-2 mr-2 bg-white/90 hover:bg-white rounded-full flex items-center justify-center shadow-sm cursor-pointer transition-colors"
            onClick={() => setShowReport(!showReport)}
          >
            <EllipsisVertical color="#333" size={18} />
          </div>
          {showReport && (
            <>
              <div
                className="fixed inset-0 z-40"
                onClick={() => setShowReport(false)}
              />
              <div
                className="absolute cursor-pointer bg-white rounded-xl shadow-lg border border-gray-100 top-11 right-2 p-1.5 z-50 min-w-[150px] transition-all animate-in fade-in zoom-in-95"
                onClick={() => {
                  setShowReport(false);
                  router.push('/delete-account');
                }}
              >
                <div className="flex items-center gap-2 px-3 py-2 text-xs font-semibold text-red-600 hover:bg-red-50 rounded-lg transition-colors">
                  <Trash2 size={14} className="text-red-500" />
                  Delete account
                </div>
              </div>
            </>
          )}
        </div>
        <div className="absolute w-full -bottom-14 flex items-center justify-center">
          <div className="h-24 w-24 bg-gray-200 rounded-full overflow-hidden relative">
            <img
              src={image ? BUCKET_ROOT + image : Profiles.src}
              alt="user"
              className="h-full w-full object-cover"
            />
            <div className="absolute bottom-1 h-6 w-6 bg-primary z-50 right-[35%] rounded-full overflow-hidden flex items-center justify-center cursor-pointer">
              <Pencil size={15} color="white" onClick={(e) => { e.preventDefault(); handleFileSelect(); }} />
              <Input
                type="file"
                accept=".jpg,.jpeg,.png"
                hidden
                ref={fileInputRef}
                onChange={handleFileChange}
                className="hidden"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Form Section */}
      <div className="w-full max-w-xl px-4">
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            {/* Name Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Name<span className="text-red-500 ml-1">*</span></label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                placeholder="Name"
                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300"
                required
                maxLength={55}
              />
            </div>

            {/* Phone Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Phone<span className="text-red-500 ml-1">*</span></label>
              <div className="flex flex-row gap-2 w-full">
                <CountryPickerModal setValue={setValue} value={valued} />
                <input
                  type="text"
                  name="phone"
                  value={formData.phone}
                  onChange={(e: any) => {
                    const numericValue = e.target.value.replace(/\D/g, "");
                    setFormData((prevState) => ({
                      ...prevState,
                      phone: numericValue,
                    }));
                  }}
                  placeholder="Phone number..."
                  className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300"
                  required
                  minLength={valued?.min_length || 6}
                  maxLength={valued?.max_length || 15}
                />
              </div>
            </div>

            {/* Email Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Email<span className="text-red-500 ml-1">*</span></label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder="Email..."
                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300"
                required
              />
            </div>

            {/* Date of Birth Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Date of Birth<span className="text-red-500 ml-1">*</span></label>
              <input
                type="date"
                name="dob"
                value={formData.dob}
                onChange={handleChange}
                placeholder="Date of Birth"
                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300"
                required
                max={new Date().toISOString().split("T")[0]}
              />
            </div>

            {/* Anniversary Date Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Anniversary Date</label>
              <input
                type="date"
                name="anniversary_date"
                value={formData.anniversary_date}
                onChange={handleChange}
                placeholder="Anniversary Date"
                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300"
                max={new Date().toISOString().split("T")[0]}
              />
            </div>

            {/* Gender Input */}
            <div className="flex flex-col gap-2">
              <label className="text-[#828282]">Gender<span className="text-red-500 ml-1">*</span></label>
              <select
                name="gender"
                value={formData.gender}
                onChange={handleChange}
                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-1 focus:ring-gray-300 capitalize"
                required
              >
                <option value="" disabled>
                  Select gender
                </option>
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
              </select>
            </div>

            {/* Button Logic */}
            {verify ? (
              <div className="flex flex-col sm:flex-row gap-2">
                {userInfo?.email !== formData?.email && (
                  <button
                    type="button"
                    onClick={(e) => {
                      e.preventDefault();
                      setIsOpen1(true);
                    }}
                    className="w-full py-3 px-4 bg-primary mt-4 hover:bg-primary/90 text-center text-white font-medium rounded-md transition duration-200"
                  >
                    Verify E-mail
                  </button>
                )}
                {(userInfo?.phone !== formData?.phone ||
                  userInfo?.country_code !== "+" + valued?.dial_code) && (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.preventDefault();
                        setIsOpen(true);
                      }}
                      className="w-full py-3 px-4 bg-primary mt-4 hover:bg-primary/90 text-center text-white font-medium rounded-md transition duration-200"
                    >
                      Verify Phone
                    </button>
                  )}
              </div>
            ) : (
              <Button
                type="submit"
                className="w-full py-3 px-4 bg-primary mt-4 hover:bg-primary text-center text-white font-medium rounded-md transition duration-200"
              >
                Save changes
              </Button>
            )}
          </div>
        </form>
      </div>
      <Modal
        isOpen={isOpen}
        description=""
        onClose={() => setIsOpen(false)}
        title={"Verify Phone"}
      >
        <div className="w-full p-2 flex flex-col items-center">
          <span className="block mt-4 mb-4 text-sm text-gray-500">
            Please input the 4-digit code that has been sent to you via phone
          </span>
          <InputOTP
            className="w-full"
            maxLength={4}
            value={otp}
            onChange={setOtp}
          >
            {[...Array(4)].map((_, index) => (
              <InputOTPGroup key={index} className="rounded-full">
                <InputOTPSlot
                  index={index}
                  className="h-14 w-14 rounded-full border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </InputOTPGroup>
            ))}
          </InputOTP>
          <button
            onClick={verifyPhone}
            className="w-full py-3 px-4 bg-primary mt-4 hover:bg-primary/90 text-center text-white font-medium rounded-md transition duration-200"
          >
            Submit
          </button>
        </div>
      </Modal>
      <Modal
        isOpen={isOpen1}
        description=""
        onClose={() => setIsOpen1(false)}
        title={"Verify Email"}
      >
        <div className="w-full p-2 flex flex-col items-center">
          <span className="block mt-4 mb-4 text-sm text-gray-500">
            Please input the 4-digit code that has been sent to you via email
          </span>
          <InputOTP
            className="w-full"
            maxLength={4}
            value={otp1}
            onChange={setOtp1}
          >
            {[...Array(4)].map((_, index) => (
              <InputOTPGroup key={index} className="rounded-full">
                <InputOTPSlot
                  index={index}
                  className="h-14 w-14 rounded-full border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </InputOTPGroup>
            ))}
          </InputOTP>
          <button
            onClick={verifyEmail}
            className="w-full py-3 px-4 bg-primary mt-4 hover:bg-primary/90 text-center text-white font-medium rounded-md transition duration-200"
          >
            Submit
          </button>
        </div>
      </Modal>
    </div>
  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <Profile />
    </DashboardLayout>
  );
}
