"use client";

import Image from "next/image";
import { FiCopy, FiEdit } from "react-icons/fi";
import Button from "../../../../components/ui/Button";
import { useAppSelector } from "../../../../hooks/useAppRedux";
import useRegenerateKey from "../../../../hooks/features/api-keys/useRegenerateKey";
import { useState } from "react";
import { UserImage } from "../../../../components/ui/CustomImage";
import ClientWrapper from "../../../../components/ClientWrapper";
import CustomLink from "../../../../components/ui/CustomLink";
import CustomTooltip from "../../../../components/ui/CustomTooltip";

export default function ProfilePage() {
  const [copied, setCopied] = useState(false);
  const profile = useAppSelector((state) => state.user.user);
  const { handleRegenerateKey, loading } = useRegenerateKey();

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(profile?.apiKey || "");

      setCopied(true);

      setTimeout(() => {
        setCopied(false);
      }, 2000);
    } catch (error) {
      console.error(error);
    }
  };

  const handleGenerateKey = async () => {
    try {
      await handleRegenerateKey();
    } catch (error) {
      console.log(error);
    }
  };

  if (!profile) return <ProfilePageSkeleton />;

  return (
    <ClientWrapper fallback={<ProfilePageSkeleton />}>
      <div className="px-4">
        <div className="mx-auto max-w-229 space-y-6">
          <div className="glass-card-v2 rounded-xl p-4 md:p-6">
            <div className="relative z-10">
              <h2 className="font-heading text-lg font-semibold text-heading mb-5">
                My Profile
              </h2>
              <div className="mb-5 flex flex-col gap-4 sm:flex-row items-center justify-between">
                <div className="flex flex-col gap-4 sm:flex-row items-center text-center sm:text-left">
                  <div className="relative h-22.5 w-22.5 overflow-hidden rounded-full border-3 border-badge">
                    <UserImage
                      src={profile?.profilePicture}
                      alt="Profile"
                      className="object-cover w-full h-full"
                    />
                  </div>

                  <div>
                    <h2 className="font-body text-lg font-bold text-heading md:text-xl mb-2">
                      {profile.firstName} {profile.lastName}
                    </h2>

                    <div className="mt-2 flex flex-col sm:flex-row flex-wrap items-center gap-1 xl:gap-3">
                      <span className="font-body rounded-full flex items-center gap-2 border border-badge bg-white p-1.5 px-2.5 xl:px-2.5 xl:py-1.5 text-sm xl:text-base font-medium text-link">
                        <Image
                          src="/images/credits-icon.svg"
                          alt="Credits Icon"
                          width={20}
                          height={20}
                          className="h-5 w-5 object-contain"
                        />{" "}
                        {profile?.balance || 0} Credits left!
                      </span>

                      <CustomLink
                        href="/dashboard/packages"
                        className="text-base font-body font-medium text-link-1 cursor-pointer"
                      >
                        {" "}
                        Upgrade Now{" "}
                      </CustomLink>
                    </div>
                  </div>
                </div>
                <Button
                  icon={<FiEdit size={18} />}
                  BtnInnerclassName=""
                  href="/edit-profile"
                >
                  Edit Profile
                </Button>
              </div>
              <div className="divide-y divide-[#DDD7F0]">
                <InfoRow label="Email" value={profile.email} />
                <InfoRow
                  label="Phone Number"
                  value={`${profile.dialCode} ${profile.mobileNumber}`}
                />

                <div className="flex flex-col gap-3 pt-3.5 sm:flex-row items-center sm:justify-between">
                  <div className="w-full sm:w-auto">
                    <p className="font-semibold text-heading font-body text-base">
                      Password
                    </p>
                    <p className="mt-0.5 xl:mt-1 text-sm xl:text-base text-text">
                      ****************
                    </p>
                  </div>

                  <Button
                    variant="white"
                    buttonClassName="!shadow-none mt-3 sm:mt-0"
                    BtnInnerclassName="!text-link"
                    href="/change-password"
                  >
                    Change Password
                  </Button>
                </div>
              </div>
            </div>
          </div>

          {/* License Key */}
          <div className="glass-card-v2 rounded-xl p-4 md:p-6">
            <div className="relative z-10">
              <div className="mb-5 flex items-center gap-2">
                <h2 className="font-heading text-lg font-semibold text-heading">
                  License Key
                </h2>

                <CustomTooltip forWhat="regenerate-key" />
              </div>
              <div className="flex gap-5 flex-wrap items-center justify-between">
                <div>
                  <p className="font-semibold text-heading font-body text-base">
                    Key Generated
                  </p>

                  <div className="mt-2 flex items-center gap-3">
                    <p className="text-sm xl:text-lg font-medium text-text">
                      {profile.apiKey
                        ? profile.apiKey.length > 20
                          ? `${profile.apiKey.slice(0, 20)}...`
                          : profile.apiKey
                        : "There is no API key. Please generate one."}
                    </p>

                    <div className="relative">
                      {profile.apiKey && (
                        <button
                          onClick={handleCopy}
                          className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-lg gradient1 text-white"
                        >
                          <FiCopy size={14} />
                        </button>
                      )}

                      {copied && (
                        <div className="absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-md bg-black px-3 py-1 text-xs text-white shadow-lg animate-in fade-in duration-200">
                          Copied!
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                <Button
                  variant="white"
                  onClick={handleGenerateKey}
                  buttonClassName="!shadow-none"
                  BtnInnerclassName="!text-linkwhitespace-nowrap"
                >
                  {loading ? "Generating..." : "Generate New Key"}
                </Button>
              </div>
            </div>
          </div>

          {/* Account Management */}
          {/* <div className="glass-card-v2 rounded-xl p-4 md:p-6">
            <div className="relative z-10">
              <h2 className="font-heading text-lg font-semibold text-heading mb-5">
                Account Management
              </h2>

              <div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <p className="font-semibold text-danger font-body text-lg">
                    Delete Account
                  </p>
                  <p className="mt-0.5 xl:mt-1 text-sm xl:text-base text-text font-medium">
                    Delete your Klebo AI Account. All your data will be
                    permanently deleted.
                  </p>
                </div>
                <Button
                  variant="white"
                  buttonClassName="!shadow-none !p-0 "
                  BtnInnerclassName="!text-danger border-1 border-danger-400  whitespace-nowrap"
                >
                  Delete Account
                </Button>
              </div>
            </div>
          </div> */}
        </div>
      </div>
    </ClientWrapper>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="py-3 xl:py-3.5 first:pt-0">
      <p className="font-semibold text-heading font-body text-base">{label}</p>
      <p className="mt-0.5 xl:mt-1 text-sm xl:text-base text-text">{value}</p>
    </div>
  );
}

function ProfilePageSkeleton() {
  return (
    <div className="mx-auto max-w-229 space-y-6 animate-pulse">
      <div className="glass-card-v2 rounded-xl p-4 md:p-6">
        <div className="mb-5 h-7 w-32 rounded bg-gray-200" />

        <div className="mb-5 flex flex-col items-center justify-between gap-4 sm:flex-row">
          <div className="flex flex-col items-center gap-4 text-center sm:flex-row sm:text-left">
            <div className="h-22.5 w-22.5 rounded-full border-3 border-gray-200 bg-gray-200" />

            <div>
              <div className="mb-3 h-6 w-44 rounded bg-gray-200" />

              <div className="mt-2 flex flex-col flex-wrap items-center gap-2 sm:flex-row xl:gap-3">
                <div className="h-9 w-40 rounded-full bg-gray-200" />
                <div className="h-5 w-28 rounded bg-gray-200" />
              </div>
            </div>
          </div>

          <div className="h-11 w-36 rounded-xl bg-gray-200" />
        </div>

        <div className="divide-y divide-[#DDD7F0]">
          {Array.from({ length: 2 }).map((_, index) => (
            <div
              key={index}
              className="flex flex-col gap-2 py-4 sm:flex-row sm:items-center sm:justify-between"
            >
              <div className="h-5 w-28 rounded bg-gray-200" />
              <div className="h-5 w-52 rounded bg-gray-200" />
            </div>
          ))}

          <div className="flex flex-col gap-3 pt-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <div className="mb-2 h-5 w-24 rounded bg-gray-200" />
              <div className="h-5 w-36 rounded bg-gray-200" />
            </div>

            <div className="h-11 w-44 rounded-xl bg-gray-200" />
          </div>
        </div>
      </div>

      <div className="glass-card-v2 rounded-xl p-4 md:p-6">
        <div className="mb-5 h-7 w-32 rounded bg-gray-200" />

        <div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <div className="mb-3 h-5 w-32 rounded bg-gray-200" />

            <div className="mt-2 flex items-center gap-3">
              <div className="h-5 w-56 rounded bg-gray-200" />
              <div className="h-7 w-7 rounded-lg bg-gray-200" />
            </div>
          </div>

          <div className="h-11 w-44 rounded-xl bg-gray-200" />
        </div>
      </div>

      <div className="glass-card-v2 rounded-xl p-4 md:p-6">
        <div className="mb-5 h-7 w-48 rounded bg-gray-200" />

        <div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <div className="mb-2 h-6 w-40 rounded bg-gray-200" />
            <div className="h-5 w-72 max-w-full rounded bg-gray-200" />
          </div>

          <div className="h-11 w-40 rounded-xl bg-gray-200" />
        </div>
      </div>
    </div>
  );
}
