import React, { useEffect, useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { CreditCard } from 'lucide-react';
import { PageContainer } from '@/components/ui/Typography';
import { PageHeader } from '@/components/layout/PageHeader';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { ToggleSwitch } from '@/components/ui/ToggleSwitch';
import { formatDateTime } from '@/utils/formatters';
import { usePaymentCard, useUpdatePaymentCard } from '../core/_hooks';
import { persianToEnglish } from '@/utils/numberUtils';

const cardSchema = yup.object({
  bank_name: yup.string().required('نام بانک الزامی است'),
  card_number: yup
    .string()
    .required('شماره کارت الزامی است')
    .test('length', 'شماره کارت باید ۱۶ رقم باشد', (value) => {
      const cleaned = value ? persianToEnglish(value).replace(/\s/g, '') : '';
      return cleaned.length === 16;
    })
    .test('numeric', 'شماره کارت باید فقط عدد باشد', (value) => {
      const cleaned = value ? persianToEnglish(value).replace(/\s/g, '') : '';
      return /^\d+$/.test(cleaned);
    }),
  name: yup.string().required('نام صاحب کارت الزامی است'),
  is_active: yup.boolean().default(true),
});

type CardFormData = yup.InferType<typeof cardSchema>;

const formatCardNumber = (value: string): string => {
  const cleaned = persianToEnglish(value).replace(/\s/g, '');
  const groups = cleaned.match(/.{1,4}/g);
  return groups ? groups.join(' ') : cleaned;
};

const CardFormPage = () => {
  const { data, isLoading, error } = usePaymentCard();
  const { mutate: updateCard, isPending } = useUpdatePaymentCard();
  const [cardNumberDisplay, setCardNumberDisplay] = useState('');

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    control,
  } = useForm<CardFormData>({
    resolver: yupResolver(cardSchema),
    defaultValues: {
      bank_name: '',
      card_number: '',
      name: '',
      is_active: true,
    },
  });

  const isActive = watch('is_active');

  useEffect(() => {
    if (data) {
      setValue('bank_name', data.bank_name || '');
      setValue('name', data.name || '');
      setValue('is_active', data.is_active);
      const formatted = formatCardNumber(data.card_number || '');
      setCardNumberDisplay(formatted);
      setValue('card_number', data.card_number || '');
    }
  }, [data, setValue]);

  const handleCardNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const cleaned = persianToEnglish(value).replace(/\s/g, '');
    
    if (cleaned.length <= 16 && /^\d*$/.test(cleaned)) {
      const formatted = formatCardNumber(cleaned);
      setCardNumberDisplay(formatted);
      setValue('card_number', cleaned, { shouldValidate: true });
    }
  };

  const onSubmit = (formData: CardFormData) => {
    const cleanedCardNumber = persianToEnglish(formData.card_number).replace(/\s/g, '');
    
    updateCard({
      bank_name: formData.bank_name,
      card_number: cleanedCardNumber,
      name: formData.name,
      is_active: formData.is_active,
    });
  };


  if (isLoading) {
    return (
      <PageContainer>
        <PageContainer>
          <div className="space-y-6 animate-pulse">
            <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
            <div className="card p-6 space-y-6">
              {[...Array(4)].map((_, i) => (
                <div key={i}>
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
                  <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
                </div>
              ))}
            </div>
          </div>
        </PageContainer>
      </PageContainer>
    );
  }

  if (error && !data) {
    return (
      <PageContainer>
        <div className="text-center py-12">
          <p className="text-red-600 dark:text-red-400">
            خطا در بارگذاری اطلاعات کارت
          </p>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <PageHeader
        title="پرداخت کارت به کارت"
        subtitle="مدیریت اطلاعات کارت و فعال/غیرفعال کردن روش پرداخت"
        icon={CreditCard}
      />

      {data?.updated_at && (
        <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
          <p className="text-sm text-blue-800 dark:text-blue-200">
            آخرین به‌روزرسانی: {formatDateTime(data.updated_at)}
          </p>
        </div>
      )}

      <form
        onSubmit={handleSubmit(onSubmit)}
        className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6 space-y-6"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <Input
              label="نام بانک"
              {...register('bank_name')}
              error={errors.bank_name?.message}
              placeholder="مثال: بانک ملی"
            />
          </div>

          <div>
            <Controller
              name="card_number"
              control={control}
              render={({ field }) => (
                <Input
                  label="شماره کارت"
                  value={cardNumberDisplay}
                  onChange={handleCardNumberChange}
                  error={errors.card_number?.message}
                  placeholder="1234 5678 9012 3456"
                  maxLength={19}
                />
              )}
            />
          </div>

          <div className="md:col-span-2">
            <Input
              label="نام صاحب کارت"
              {...register('name')}
              error={errors.name?.message}
              placeholder="مثال: علی احمدی"
            />
          </div>

          <div className="md:col-span-2">
            <div className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
              <div>
                <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  فعال بودن روش پرداخت
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  در صورت غیرفعال بودن، این روش پرداخت در صفحه پرداخت نمایش داده نمی‌شود
                </p>
              </div>
              <ToggleSwitch
                checked={isActive}
                onChange={(checked) => setValue('is_active', checked)}
                disabled={isPending}
              />
            </div>
          </div>
        </div>

        <div className="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
          <Button
            type="submit"
            variant="primary"
            loading={isPending}
            disabled={isPending}
          >
            ذخیره تغییرات
          </Button>
        </div>
      </form>
    </PageContainer>
  );
};

export default CardFormPage;

