import React, { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { Plus } from 'lucide-react';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { useWalletCredit } from '../core/_hooks';
import { WalletCreditRequest, WalletType } from '../core/_credit-models';
import { formatCurrency } from '@/utils/formatters';
import { formatWithThousands, persianToEnglish } from '@/utils/numberUtils';
import { useSearchUsers, useUsers } from '@/pages/users-admin/core/_hooks';
import { UserFilters } from '@/pages/users-admin/core/_models';

const schema = yup.object({
  user_id: yup.number().required('شناسه کاربر الزامی است').positive('شناسه کاربر باید عدد مثبت باشد'),
  wallet_type: yup.string().oneOf(['rial', 'gold18k'], 'نوع کیف پول نامعتبر است').required('نوع کیف پول الزامی است'),
  amount: yup.number().required('مبلغ الزامی است').positive('مبلغ باید عدد مثبت باشد'),
  reason: yup.string().required('دلیل شارژ الزامی است').min(10, 'دلیل باید حداقل ۱۰ کاراکتر باشد'),
  admin_note: yup.string().optional().default(''),
});

type FormData = yup.InferType<typeof schema>;

const WalletCreditPage = () => {
  const { mutate: creditWallet, isPending } = useWalletCredit();
  const [successData, setSuccessData] = useState<{ new_balance: number; message: string } | null>(null);
  const [searchText, setSearchText] = useState('');
  const [debouncedText, setDebouncedText] = useState('');
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [amountDisplay, setAmountDisplay] = useState('');

  const {
    register,
    setValue,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<FormData>({
    resolver: yupResolver(schema) as any,
    defaultValues: {
      wallet_type: 'rial',
      admin_note: '',
    },
  });

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedText(searchText);
    }, 300);
    return () => clearTimeout(handler);
  }, [searchText]);

  const { data: usersData, isLoading: isUsersLoading } = useUsers({
    limit: 20,
    offset: 0,
  });

  const searchFilters = useMemo<UserFilters>(() => {
    if (!debouncedText) return {};
    return {
      search_text: debouncedText,
      limit: 20,
      offset: 0,
    };
  }, [debouncedText]);

  const { data: searchData, isLoading: isSearchLoading } = useSearchUsers(searchFilters);

  const userOptions = useMemo(() => {
    if (debouncedText) {
      return searchData?.users || [];
    }
    return usersData || [];
  }, [debouncedText, searchData, usersData]);

  const isLoadingUsers = debouncedText ? isSearchLoading : isUsersLoading;

  const handleSelectUser = (user: any) => {
    setValue('user_id', user.id, { shouldValidate: true, shouldDirty: true });
    setSearchText(user.phone_number);
    setIsDropdownOpen(false);
  };

  const onSubmit = (data: FormData) => {
    const payload: WalletCreditRequest = {
      user_id: data.user_id,
      wallet_type: data.wallet_type as WalletType,
      amount: data.amount,
      reason: data.reason,
      admin_note: data.admin_note || undefined,
    };

    creditWallet(payload, {
      onSuccess: (response) => {
        setSuccessData({
          new_balance: response.new_balance,
          message: response.message,
        });
        reset();
        setAmountDisplay('');
        setTimeout(() => setSuccessData(null), 5000);
      },
    });
  };

  return (
    <PageContainer>
      <PageTitle>شارژ کیف پول کاربر</PageTitle>

      {successData && (
        <div className="mb-6 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
          <p className="text-green-800 dark:text-green-200 font-medium mb-2">
            {successData.message}
          </p>
          <p className="text-sm text-green-700 dark:text-green-300">
            موجودی جدید: {formatCurrency(successData.new_balance)}
          </p>
        </div>
      )}

      <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
        <form onSubmit={handleSubmit(onSubmit as any)} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                شناسه کاربر <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Input
                  value={searchText}
                  onChange={(e) => {
                    const normalized = persianToEnglish(e.target.value).replace(/[^\d]/g, '');
                    setSearchText(normalized);
                    setIsDropdownOpen(true);
                    setValue('user_id', undefined as any, { shouldValidate: true, shouldDirty: true });
                  }}
                  onFocus={() => setIsDropdownOpen(true)}
                  onBlur={() => setTimeout(() => setIsDropdownOpen(false), 150)}
                  error={errors.user_id?.message}
                  placeholder="جستجو با شماره موبایل"
                />
                <input
                  type="hidden"
                  {...register('user_id')}
                />
                {isDropdownOpen && (
                  <div className="absolute z-20 mt-2 w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-lg max-h-60 overflow-y-auto">
                    {isLoadingUsers && (
                      <div className="p-3 text-sm text-gray-500 dark:text-gray-400">
                        در حال بارگذاری...
                      </div>
                    )}
                    {!isLoadingUsers && userOptions.length === 0 && (
                      <div className="p-3 text-sm text-gray-500 dark:text-gray-400">
                        کاربری یافت نشد
                      </div>
                    )}
                    {!isLoadingUsers && userOptions.map((user: any) => (
                      <button
                        key={user.id}
                        type="button"
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => handleSelectUser(user)}
                        className="w-full text-right px-4 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                      >
                        <div className="text-sm text-gray-900 dark:text-gray-100">
                          {user.first_name} {user.last_name}
                        </div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">
                          {user.phone_number}
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                نوع کیف پول <span className="text-red-500">*</span>
              </label>
              <select
                {...register('wallet_type')}
                className={`input ${errors.wallet_type ? 'border-red-500' : ''}`}
              >
                <option value="rial">ریال</option>
                <option value="gold18k">طلا ۱۸ عیار</option>
              </select>
              {errors.wallet_type && (
                <p className="text-sm text-red-600 dark:text-red-400 mt-1">
                  {errors.wallet_type.message}
                </p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                مبلغ (تومان) <span className="text-red-500">*</span>
              </label>
              <Input
                type="text"
                value={amountDisplay}
                onChange={(e) => {
                  const normalized = persianToEnglish(e.target.value).replace(/[^\d]/g, '');
                  const numericValue = normalized ? Number(normalized) : undefined;
                  setAmountDisplay(normalized ? formatWithThousands(Number(normalized)) : '');
                  setValue('amount', numericValue as any, { shouldValidate: true, shouldDirty: true });
                }}
                error={errors.amount?.message}
                placeholder="مثلاً 1,000,000"
                numeric
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              دلیل شارژ <span className="text-red-500">*</span>
            </label>
            <textarea
              {...register('reason')}
              rows={3}
              className={`input resize-none ${errors.reason ? 'border-red-500' : ''}`}
              placeholder="مثلاً: شارژ کیف پول کاربر به علت مرجوع کردن یک سفارش به مبلغ ۱ میلیون"
            />
            {errors.reason && (
              <p className="text-sm text-red-600 dark:text-red-400 mt-1">
                {errors.reason.message}
              </p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              یادداشت ادمین (اختیاری)
            </label>
            <textarea
              {...register('admin_note')}
              rows={2}
              className="input resize-none"
              placeholder="مثلاً: شارژ کیف طلا"
            />
          </div>

          <div className="flex items-center justify-end gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <Button
              type="button"
              variant="secondary"
              onClick={() => reset()}
              disabled={isPending}
            >
              پاک کردن
            </Button>
            <Button
              type="submit"
              disabled={isPending}
              loading={isPending}
            >
              <Plus className="h-4 w-4 ml-2" />
              شارژ کیف پول
            </Button>
          </div>
        </form>
      </div>
    </PageContainer>
  );
};

export default WalletCreditPage;
