'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import ProtectedRoute from '@/components/ProtectedRoute';
import { getMetaAccounts } from '@/modules/api/meta-account-step/getMetaAccounts';
import { getBankAccounts, getBankAccountByMetaId } from '@/modules/api/bank/getBankAccounts';
import { submitWithdrawal } from '@/modules/api/withdraw/submitWithdrawal';

function WithdrawCreateContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const metaAccountIdParam = searchParams.get('meta_account_id');
  const [metaAccounts, setMetaAccounts] = useState([]);
  const [bankAccounts, setBankAccounts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  const [formData, setFormData] = useState({
    meta_account_id: '',
    user_bank_account_id: '',
    amount: '', // raw value (number string)
    // currency_rate: '1',
  });

  // For display only
  const [amountDisplay, setAmountDisplay] = useState('');

  const fetchBankAccountsForMetaId = async (metaId) => {
    if (!metaId) {
      setBankAccounts([]);
      return;
    }

    try {
      const res = await getBankAccountByMetaId(metaId);
      setBankAccounts(res?.data || []);
    } catch (err) {
      setBankAccounts([]);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const metaRes = await getMetaAccounts();
        // Filter only approved meta accounts
        const approved = metaRes?.data?.filter((acc) => acc.status === 'APPROVED') || [];
        setMetaAccounts(approved);
      } catch (err) {
        console.error('Failed to fetch data:', err);
        setError('Gagal memuat data. Silakan refresh halaman.');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (!metaAccountIdParam) {
      return;
    }

    setFormData((prev) => ({
      ...prev,
      meta_account_id: metaAccountIdParam,
      user_bank_account_id: '',
    }));

    fetchBankAccountsForMetaId(metaAccountIdParam);
  }, [metaAccountIdParam]);

  const handleInputChange = async (e) => {
    const { name, value } = e.target;
    setError('');

    if (name === 'amount') {
      // Remove all non-digit
      const raw = value.replace(/\D/g, '');
      setFormData((prev) => ({ ...prev, amount: raw }));
      // Format with dot every 3 digits from the right
      setAmountDisplay(raw.replace(/\B(?=(\d{3})+(?!\d))/g, '.'));
      return;
    }

    if (name === 'meta_account_id') {
      setFormData((prev) => ({ ...prev, meta_account_id: value, user_bank_account_id: '' }));
      await fetchBankAccountsForMetaId(value);
      return;
    }

    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const validateForm = () => {
    if (!formData.meta_account_id) {
      setError('Akun Meta harus dipilih');
      return false;
    }
    if (!formData.user_bank_account_id) {
      setError('Rekening harus dipilih');
      return false;
    }
    if (!formData.amount || Number(formData.amount) <= 0) {
      setError('Jumlah withdraw harus lebih dari 0');
      return false;
    }
    return true;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;
    setSubmitting(true);
    setError('');
    try {
      const payload = {
        meta_account_id: formData.meta_account_id,
        user_bank_account_id: formData.user_bank_account_id,
        amount: Number(formData.amount),
        // currency_rate: Number(formData.currency_rate),
      };
      await submitWithdrawal(payload);
      const redirectTarget = metaAccountIdParam
        ? `/pages/withdraw?meta_account_id=${encodeURIComponent(metaAccountIdParam)}`
        : '/pages/withdraw';
      router.push(redirectTarget);
    } catch (err) {
      console.error('Submit withdraw error:', err);
      setError(err.response?.data?.message || 'Gagal mengajukan withdraw. Silakan coba lagi.');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-white">Memuat data...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center px-4 py-40 relative">
      {/* 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="w-full max-w-lg">
        <div className="bg-[#2a2a2a]/80 backdrop-blur-sm rounded-3xl p-8 border-y-2 border-[#FCA311]">
          <h1 className="text-2xl md:text-3xl font-bold text-white text-center mb-2">
            Pengajuan Withdraw
          </h1>
          <p className="text-gray-400 text-sm text-center mb-8">
            Silakan Masukan Jumlah dan Nomer Rekening yang diinginkan
          </p>
          {error && (
            <div className="mb-6 p-3 bg-red-500/10 border border-red-500/50 text-red-400 rounded-lg text-sm">
              {error}
            </div>
          )}
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Akun Meta */}
            <div>
              <label className="block text-sm text-gray-300 mb-2">Akun Meta</label>
              <div className="relative">
                <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
                <select
                  name="meta_account_id"
                  value={formData.meta_account_id}
                  onChange={handleInputChange}
                  className="w-full pl-10 pr-4 py-3 bg-[#2a2a2a] border border-[#FCA311]/50 text-white focus:outline-none focus:border-[#FCA311] transition-all appearance-none"
                >
                  <option value="">Pilih Akun Meta</option>
                  {metaAccounts.map((acc) => (
                    <option key={acc.meta_account_id} value={acc.meta_account_id}>
                      {acc.meta_account_number || acc.meta_account_id}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            {/* Jumlah Withdraw */}
            <div>
              <label className="block text-sm text-gray-300 mb-2">Jumlah Withdraw</label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">Rp</span>
                <input
                  type="text"
                  name="amount"
                  inputMode="numeric"
                  autoComplete="off"
                  value={amountDisplay}
                  onChange={handleInputChange}
                  className="w-full pl-10 pr-4 py-3 bg-[#2a2a2a] border border-[#FCA311]/50 text-white focus:outline-none focus:border-[#FCA311] transition-all"
                  placeholder="5.500.000"
                  min="0"
                  maxLength={15}
                />
              </div>
            </div>

            {/* Currency Rate */}
            {/* <div>
              <label className="block text-sm text-gray-300 mb-2">Nilai Tukar Mata Uang</label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">
                  Rp
                </span>
                <input
                  type="number"
                  name="currency_rate"
                  value={formData.currency_rate}
                  onChange={handleInputChange}
                  className="w-full pl-10 pr-4 py-3 bg-[#2a2a2a] border border-[#FCA311]/50 text-white focus:outline-none focus:border-[#FCA311] transition-all"
                  placeholder="5,500,000"
                  min="0"
                />
              </div>
            </div> */}

            {/* Rekening */}
            <div>
              <label className="block text-sm text-gray-300 mb-2">Rekening</label>
              <div className="relative">
                <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                </svg>
                <select
                  name="user_bank_account_id"
                  value={formData.user_bank_account_id}
                  onChange={handleInputChange}
                  className="w-full pl-10 pr-4 py-3 bg-[#2a2a2a] border border-[#FCA311]/50 text-white focus:outline-none focus:border-[#FCA311] transition-all appearance-none"
                  disabled={!formData.meta_account_id}
                >
                  <option value="">Pilih Rekening</option>
                  {bankAccounts.map((bank) => (
                    <option key={bank.bank_id} value={bank.bank_id}>
                      {bank.bank_name} - {bank.account_number}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="w-full py-3 bg-linear-to-r from-[#FF5B39] to-[#FF8A4D] hover:bg-[#FF8A4D] text-white font-semibold rounded-full transition-all disabled:opacity-50 disabled:cursor-not-allowed mt-8"
            >
              {submitting ? 'Mengirim...' : 'Kirim'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default function WithdrawCreatePage() {
  return (
    <ProtectedRoute>
      <WithdrawCreateContent />
    </ProtectedRoute>
  );
}
