'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { useAuth } from '@/context/AuthContext';
import ProtectedRoute from '@/components/ProtectedRoute';
import { getMetaAccounts } from '@/modules/api/meta-account-step/getMetaAccounts';
import { getMetaAccountAmendments } from '@/modules/api/meta-account/metaAccountAmandment';
import { getUserProfile, getMyProfile } from '@/modules/api/user/userProfile';
import generateMetaAgreementFormPDF from '@/utils/metaAgreementPdf';



const STATUS_LABEL = {
  APPROVED: 'APPROVED',
  PENDING: 'PENDING',
  REJECTED: 'REJECTED',
  FAILED: 'FAILED',
};

const STATUS_TABS = ['APPROVED', 'PENDING', 'REJECTED', 'FAILED'];

function VerihubRejectedMessage() {
  const router = useRouter();

  return (
    <>
      <div className="my-6 p-3 bg-red-500/10 border border-red-500/50 text-red-400 rounded-lg text-sm">
        Pendaftaran akun anda ditolak. Silakan hubungi admin
      </div>
      <button className="my-8 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
        onClick={() => router.push('https://api.whatsapp.com/send/?phone=6285951522829&text=Helo...&type=phone_number&app_absent=0')}
      >
        Hubungi Admin
      </button>
    </>
  );
}

function ProfileContent() {
  const router = useRouter();
  const { user, logout } = useAuth();
  const [metaAccounts, setMetaAccounts] = useState([]);
  const [accountsLoading, setAccountsLoading] = useState(true);
  const [userProfile, setUserProfile] = useState(null);
  const [isProfileLoaded, setIsProfileLoaded] = useState(false);
  const [showUnverifiedPopup, setShowUnverifiedPopup] = useState(false);
  const [isLogoutPopupOpen, setIsLogoutPopupOpen] = useState(false);
  const [verihubRejected, setVerihubRejected] = useState(false);
  const [activeStatusTab, setActiveStatusTab] = useState('APPROVED');
  const [agreementLoadingId, setAgreementLoadingId] = useState('');

  useEffect(() => {
    const fetchAccounts = async () => {
      try {
        const response = await getMetaAccounts();
        if (response?.data && Array.isArray(response.data) && response.data.length > 0) {
          setMetaAccounts(response.data);
        }
      } catch (err) {
        console.error('Failed to fetch meta accounts:', err);
      } finally {
        setAccountsLoading(false);
      }
    };

    const fetchProfile = async () => {
      try {
        const response = await getUserProfile();
        if (response?.data) {
          setUserProfile(response.data);
          setShowUnverifiedPopup(response.data.status === 'UNVERIFIED');
        }
      } catch (err) {
        console.error('Failed to fetch user profile:', err);
      } finally {
        setIsProfileLoaded(true);
      }
    };

    fetchAccounts();
    fetchProfile();
  }, []);

  // const handleLogout = () => {
  //   setIsLogoutPopupOpen(true);
  // };

  const handleConfirmLogout = () => {
    setIsLogoutPopupOpen(false);
    logout();
    // Hapus seluruh localStorage
    if (typeof window !== 'undefined') {
      localStorage.clear();
    }
    router.push('/pages/auth/login-cabinet');
  };

  const handleCancelLogout = () => {
    setIsLogoutPopupOpen(false);
  };

  const handleBuatAkunBaru = async (selectedMetaAccountId = '') => {
    try {
      const response = await getMetaAccounts();
      const responseProfile = await getMyProfile();

      if (response?.data && Array.isArray(response.data) && response.data.length > 0 && responseProfile.data.verihubs_status !== 'REJECTED' && responseProfile.data.current_step !== 0) {
        const fallbackMetaAccountId = selectedMetaAccountId || response.data[0]?.meta_account_id || '';
        const target = fallbackMetaAccountId
          ? `/pages/meta-account/create-meta?meta_account_id=${encodeURIComponent(fallbackMetaAccountId)}`
          : '/pages/meta-account/create-meta';

        router.push(target);
        return;
      }

      if (response.data.length === 0 && responseProfile.data.current_step === 6 && responseProfile.data.verihubs_status === 'SUBMITTED') {
        localStorage.setItem('meta_account_step_key', 'upload-documents');
        router.push('/pages/meta-account');
        return;
      }

      if (response.data.length === 0 && responseProfile.data.current_step === 6) {
        localStorage.setItem('meta_account_step', 'already-submit');
        router.push('/pages/meta-account');
        return;
      }

      if (responseProfile.data.verihubs_status === 'REJECTED') {
        localStorage.removeItem('meta_account_step');
        localStorage.removeItem('meta_account_step_key');
        setVerihubRejected(true);
        return;
      }

      if (responseProfile.data.current_step < 6) {
        const stepMap = responseProfile.data.current_step;

        if (typeof window !== 'undefined') {
          let stepKey = '';
          switch (stepMap) {
            case 1:
              stepKey = 'address-contact';
              break;
            case 2:
              stepKey = 'employment-financial';
              break;
            case 3:
              stepKey = 'investment-emergency';
              break;
            case 4:
              stepKey = 'upload-documents';
              break;
            case 5:
              stepKey = 'legal-final-submit';
              break;
            default:
              localStorage.removeItem('meta_account_step_key');
          }

          if (stepKey) {
            localStorage.setItem('meta_account_step_key', stepKey);
          }
        }

        router.push('/pages/meta-account');
        return;
      }
    } catch (err) {
      console.error('Cek meta account gagal:', err);
    }

    localStorage.removeItem('meta_account_step');
    router.push('/pages/meta-account');
  };

  const handleDownloadAgreement = async (metaAccountId) => {
    if (!metaAccountId) return;

    setAgreementLoadingId(metaAccountId);

    try {
      const response = await getMetaAccountAmendments(metaAccountId);
      await generateMetaAgreementFormPDF(response);
    } catch (err) {
      console.error('Failed to download agreement PDF:', err);
    } finally {
      setAgreementLoadingId('');
    }
  };

  const getStatusLabel = (status) => STATUS_LABEL[status] || status || '-';

  const handleUnverifiedContinue = () => {
    const verificationEmail = userProfile?.email || '';

    if (typeof window !== 'undefined') {
      localStorage.clear();
      window.location.replace(
        verificationEmail
          ? `/pages/auth/verify-email?email=${encodeURIComponent(verificationEmail)}&resend=1`
          : '/pages/auth/verify-email?resend=1'
      );
    }
  };

  // Loading overlay jika data belum siap
  if (accountsLoading || !isProfileLoaded || !userProfile) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
        <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-[#FDD168]"></div>
      </div>
    );
  }

  if (showUnverifiedPopup) {
    return (
      <div className="relative min-h-screen overflow-hidden px-6 py-50">
        <div className="absolute inset-0 bg-cover bg-center bg-no-repeat bg-[url('/images/bg_grid.png')] -z-10"></div>
        <div className="absolute inset-0 bg-linear-to-tr from-[#190D66]/70 via-[#1D0D80]/70 to-[#190D66]/70 -z-10"></div>

        <div className="fixed inset-0 z-50 flex items-center justify-center px-4">
          <div className="absolute inset-0 bg-black/70 backdrop-blur-[3px]"></div>

          <div className="relative w-full max-w-md rounded-4xl border-y border-[#FCA311] bg-linear-to-br from-[#190D66] via-[#161045]/20 to-[#161045] px-8 pb-10 pt-8 shadow-[0_24px_90px_rgba(0,0,0,0.68)] backdrop-blur-sm">
            <div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-2xl border-4 border-[#FCA311] bg-[#1D0D80]/40">
              <svg className="h-9 w-9 text-[#FCA311]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </div>

            <h2 className="mx-auto mb-4 max-w-72 text-center text-3xl font-bold leading-tight text-white">
              Akun Belum Terverifikasi
            </h2>

            <p className="mx-auto mb-10 max-w-[320px] text-center text-base leading-relaxed text-[#D2D2D2]">
              Silakan selesaikan verifikasi terlebih dahulu. Kami akan mengirim ulang OTP ke email Anda agar proses verifikasi bisa dilanjutkan.
            </p>

            <div className="flex justify-center">
              <button
                onClick={handleUnverifiedContinue}
                className="w-full px-8 py-3 border-y border-[#FDD168] bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] font-semibold rounded-full transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Verifikasi Sekarang
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Sort metaAccounts so APPROVED accounts appear at the top
  const sortedMetaAccounts = [...metaAccounts].sort((a, b) => {
    if (a.status === 'APPROVED' && b.status !== 'APPROVED') return -1;
    if (a.status !== 'APPROVED' && b.status === 'APPROVED') return 1;
    return 0;
  });

  const filteredMetaAccounts = sortedMetaAccounts.filter((acc) => acc.status === activeStatusTab);

  return (
    <>
    <div className="min-h-screen relative px-6 py-50">
      {/* Background */}
      <div className="absolute inset-0 bg-cover bg-center bg-no-repeat bg-[url('/images/bg_grid.png')] -z-10"></div>
      <div className="absolute inset-0 bg-[#0d0d0d]/90 -z-10"></div>

      <div className="max-w-5xl mx-auto">
        {/* Welcome */}
        <h1 className="text-2xl md:text-3xl font-bold text-white mb-8">
          Selamat Datang
        </h1>

        {/* Top section: form + action button */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
          {/* Left - Profile Info */}
          <div className="space-y-5">
            {/* Email */}
            <div>
              <label className="block text-sm text-gray-300 mb-1">Email</label>
              <div className="flex items-center gap-3 border border-[#CCAE66]/80 rounded-xl px-4 py-3 bg-transparent">
                <svg className="w-5 h-5 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                <span className="text-white text-sm">{userProfile?.email || '-'}</span>
              </div>
            </div>

            {/* Nomor Telepon */}
            {/* <div>
              <label className="block text-sm text-gray-300 mb-1">Nomor Telepon</label>
              <div className="flex items-center gap-3 border border-[#CCAE66] rounded-xl px-4 py-3 bg-transparent">
                <svg className="w-5 h-5 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                </svg>
                <span className="text-white text-sm">{userProfile?.mobile_phone_number || '-'}</span>
              </div>
            </div> */}
          </div>
        </div>        
        
        {verihubRejected && <VerihubRejectedMessage />}

        {/* Meta Accounts Section */}
        <div className="mb-10">
          {accountsLoading ? (
            <div className="text-white text-sm">Memuat data akun...</div>
          ) : metaAccounts.length > 0 ? (
            <>
              <div className="flex flex-wrap gap-3 mb-6">
                {STATUS_TABS.map((status) => {
                  const isActive = activeStatusTab === status;
                  const statusCount = metaAccounts.filter((acc) => acc.status === status).length;

                  return (
                    <button
                      key={status}
                      type="button"
                      onClick={() => setActiveStatusTab(status)}
                      className={`px-4 py-2 rounded-full border text-sm font-semibold transition-all ${
                        isActive
                          ? 'bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] border-[#FDD168] text-white'
                          : 'bg-transparent border-[#CCAE66]/40 text-gray-300 hover:border-[#FDD168] hover:text-white'
                      }`}
                    >
                      {status} <span className="ml-1 opacity-80">({statusCount})</span>
                    </button>
                  );
                })}
              </div>

              {filteredMetaAccounts.length > 0 ? (
                <>
                  {/* Table */}
                  <div className="overflow-x-auto overflow-y-auto max-h-130 rounded-xl border border-[#1D0D80]/20 mb-6">
                    <table className="w-full text-sm text-center">
                      <thead>
                        <tr className="sticky top-0 bg-[#0a0a0a] z-10 border-b border-[#CCAE66]">
                          {/* {['Nomor Akun Meta', 'Jenis Produk', 'Jenis Akun', 'Rate', 'Status', 'Keterangan', 'Aggrement', ''].map((h) => ( */}
                          {['No.', 'Nomor Akun Meta', 'Produk', 'Jenis Produk', 'Jenis Akun', 'Rate', 'Status', 'Keterangan', 'Aggrement', ''].map((h) => (
                            <th key={h} className="px-4 py-3 text-white font-semibold whitespace-nowrap">
                              {h}
                            </th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {filteredMetaAccounts.map((acc, index) => (
                          <tr key={acc.meta_account_id} className="border-b border-[#CCAE66] hover:bg-[#FCA311] transition-colors">
                            <td className="px-4 py-3 text-white">{index + 1}</td>
                            <td className="px-4 py-3 text-white">{acc.meta_account_number || '-'}</td>
                            <td className="px-4 py-3 text-white">{acc.product_name || '-'}</td>
                            <td className="px-4 py-3 text-white">{acc.asset_class || '-'}</td>
                            <td className="px-4 py-3 text-white">{acc.product_type || '-'}</td>
                            <td className="px-4 py-3 text-white">{acc.product_rate || '-'}</td>
                            <td className="px-4 py-3 text-white">{getStatusLabel(acc.status)}</td>
                            <td className="px-4 py-3 text-white">
                              {acc.status === 'REJECTED' || acc.status === 'FAILED' ? (
                                <button
                                  onClick={() => handleBuatAkunBaru(acc.meta_account_id)}
                                  className="text-white hover:underline text-xs"
                                >
                                  Daftar Ulang
                                </button>
                              ) : '-'}
                            </td>
                            <td className="px-4 py-3 text-white">
                              <button
                                type="button"
                                onClick={() => handleDownloadAgreement(acc.meta_account_id)}
                                disabled={acc.status !== 'APPROVED' || agreementLoadingId === acc.meta_account_id}
                                className="px-3 py-1.5 border border-[#FDD168] rounded-lg bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-white text-xs font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                {agreementLoadingId === acc.meta_account_id ? 'Downloading...' : 'download'}
                              </button>
                            </td>
                            {/* <td className="px-4 py-3 text-white">
                              {acc.agreement_file ? (
                                <a
                                  href={acc.agreement_file}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-white hover:underline text-xs"
                                >
                                  kontrak.pdf
                                </a>
                              ) : '-'}
                            </td> */}
                            <td className="px-4 py-3">
                              <div className="flex items-center justify-center gap-2">
                                <button
                                  onClick={() => {
                                    if (acc.meta_account_id) {
                                      router.push(`/pages/deposit?meta_account_id=${encodeURIComponent(acc.meta_account_id)}`);
                                    } else {
                                      router.push('/pages/deposit');
                                    }
                                  }}
                                  className="px-3 py-1.5 border border-[#FDD168] rounded-lg bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-white text-xs font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
                                  title="Deposit"
                                  disabled={acc.status !== 'APPROVED'}
                                >
                                  DEPOSIT
                                </button>
                                <button
                                  onClick={() => {
                                    if (acc.meta_account_id) {
                                      router.push(`/pages/withdraw?meta_account_id=${encodeURIComponent(acc.meta_account_id)}`);
                                    } else {
                                      router.push('/pages/withdraw');
                                    }
                                  }}
                                  className="px-3 py-1.5 border border-[#FDD168] rounded-lg bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-white text-xs font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
                                  title="Withdraw"
                                  disabled={acc.status !== 'APPROVED'}
                                >
                                  WITHDRAW
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  {/* Buat Akun Baru */}
                  <button
                    onClick={() => handleBuatAkunBaru(filteredMetaAccounts[0]?.meta_account_id)}
                    className="px-8 py-3 border border-[#FDD168] text-white font-semibold rounded-full bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-sm"
                  >
                    Buat Akun Baru
                  </button>
                </>
              ) : (
                <div className="rounded-xl border border-[#CCAE66]/30 p-6 text-center text-gray-300">
                  Tidak ada data untuk status {activeStatusTab}.
                </div>
              )}
            </>
          ) : (
            /* No Account */
            <div>
              <h2 className="text-xl md:text-2xl font-bold text-white mb-2">
                Anda Tidak Memiliki Data Akun
              </h2>
              <p className="text-gray-400 text-sm mb-6">
                Daftar akun Meta terlebih dahulu disini.
              </p>
              <button
                onClick={() => handleBuatAkunBaru(metaAccounts[0]?.meta_account_id)}
                className="px-8 py-3 border border-[#FDD168] text-white font-semibold rounded-full bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-sm"
              >
                Daftar Akun Baru
              </button>
            </div>
          )}
        </div>

        {/* Bottom Buttons */}
        <div className="flex flex-col md:flex-row gap-4 mt-30 md:justify-between">
          {/* <button
            onClick={handleGantiPassword}
            className="px-10 py-3 border border-[#FDD168] text-white font-semibold rounded-full bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-sm"
          >
            Ganti Password
          </button> */}
          {/* <button
            onClick={handleLogout}
            className="px-10 py-3 border border-[#FDD168] text-white font-semibold rounded-full bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] transition-all text-sm"
          >
            Log Out
          </button> */}
        </div>
      </div>

      {isLogoutPopupOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center px-4">
          <div className="absolute inset-0 bg-black/75 backdrop-blur-[2px]" onClick={handleCancelLogout}></div>

          <div className="relative w-full max-w-md rounded-3xl border-y border-[#E2A22D] bg-linear-to-b from-[#515151] via-[#303030] to-[#190D66] px-8 pb-10 pt-7 shadow-[0_20px_80px_rgba(0,0,0,0.65)]">
            <button
              onClick={handleCancelLogout}
              className="absolute right-4 top-4 flex h-10 w-10 items-center justify-center rounded-full border-4 border-[#C9C9C9] text-2xl font-bold leading-none text-[#C9C9C9] hover:opacity-80"
              aria-label="Tutup popup"
            >
              x
            </button>

            <h2 className="mx-auto mb-7 mt-8 max-w-72 text-center text-4xl font-bold leading-tight text-white md:text-3xl">
              Anda Yakin Ingin Keluar?
            </h2>

            <div className="mx-auto mb-7 flex h-32 w-40 items-center justify-center">
              <Image
                src="/icon/logout.png"
                alt="Logout"
                width={72}
                height={72}
                className="h-25 w-25 object-contain"
              />
            </div>

            <p className="mx-auto mb-12 max-w-[320px] text-center text-[20px] leading-tight text-[#D2D2D2] md:text-[18px]">
              Data akan tersimpan dan akan kembali ketika Anda masuk kembali
            </p>

            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-center sm:gap-4">
              <button
                onClick={handleCancelLogout}
                className="w-full rounded-full bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] px-8 py-3 text-xl font-semibold text-white transition-all sm:w-40"
              >
                Batal
              </button>
              <button
                onClick={handleConfirmLogout}
                className="w-full rounded-full border-y border-[#FDD168] bg-linear-to-t from-[#272B39] to-[#3D3D3D] px-8 py-3 text-xl font-semibold text-[#FDD168] transition-all hover:brightness-110 sm:w-40"
              >
                Keluar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
    </>
  );
}

export default function ProfilePage() {
  return (
    <ProtectedRoute>
      <ProfileContent />
    </ProtectedRoute>
  );
}
