import React, { useMemo, useState } from 'react';
import { CreditCard, Loader2, TrendingUp, CheckCircle, XCircle, DollarSign } from 'lucide-react';
import { PageContainer } from '@/components/ui/Typography';
import { PageHeader } from '@/components/layout/PageHeader';
import { ToggleSwitch } from '@/components/ui/ToggleSwitch';
import { Modal } from '@/components/ui/Modal';
import { Table } from '@/components/ui/Table';
import { formatDateTime } from '@/utils/formatters';
import { formatCurrency } from '@/utils/formatters';
import { formatWithThousands } from '@/utils/numberUtils';
import { useIPGStatus, useUpdateIPGStatus } from '../core/_hooks';
import { IPGStatus, IPG_LABELS } from '../core/_models';
import { usePaymentMethodsReport, usePaymentTransactionsReport } from '@/pages/reports/payment-statistics/core/_hooks';
import { TableColumn } from '@/types';

const getPaymentTypeLabel = (type: string): string => {
  const labels: Record<string, string> = {
    'bank-topup': 'افزایش موجودی کیف پول',
    'card-to-card': 'پرداخت به روش کارت به کارت',
    'debit-rial-wallet': 'پرداخت از کیف ریالی',
    'debit-gold18k-wallet': 'پرداخت از کیف طلا',
    unknown: 'نامشخص',
  };
  return labels[type] || type;
};

const IPGListPage = () => {
  const { data, isLoading, error } = useIPGStatus();
  const { mutate: updateStatus, isPending } = useUpdateIPGStatus();
  const [selectedPaymentType, setSelectedPaymentType] = useState<string | null>(null);
  const [isTransactionsModalOpen, setIsTransactionsModalOpen] = useState(false);

  const paymentReportFilters = useMemo(
    () => ({
      limit: 50,
      offset: 0,
      group_by_user: false,
    }),
    []
  );
  const {
    data: paymentMethodsReport,
    isLoading: isPaymentReportLoading,
    error: paymentReportError,
  } = usePaymentMethodsReport(paymentReportFilters);

  const transactionFilters = useMemo(() => {
    if (!selectedPaymentType) {
      return { limit: 0, offset: 0 } as const;
    }
    return {
      payment_type: selectedPaymentType,
      limit: 20,
      offset: 0,
      sort_by: 'date' as const,
      sort_order: 'desc' as const,
    };
  }, [selectedPaymentType]);

  const {
    data: paymentTransactionsReport,
    isLoading: isTransactionsLoading,
    error: paymentTransactionsError,
  } = usePaymentTransactionsReport(transactionFilters, isTransactionsModalOpen && !!selectedPaymentType);

  const transactionColumns: TableColumn[] = useMemo(
    () => [
      { key: 'order_number', label: 'شماره سفارش', align: 'right' },
      { key: 'customer_name', label: 'نام مشتری', align: 'right' },
      { key: 'amount', label: 'مبلغ', align: 'right' },
      { key: 'status', label: 'وضعیت', align: 'right' },
      { key: 'created_at', label: 'تاریخ', align: 'right' },
    ],
    []
  );

  const transactionTableData = (paymentTransactionsReport?.transactions || []).map((tx) => ({
    order_number: tx.order_number || '-',
    customer_name: tx.customer_name || '-',
    amount: formatCurrency(tx.amount),
    status: tx.status,
    created_at: formatDateTime(tx.created_at),
  }));

  const handleOpenTransactionsModal = (paymentType: string) => {
    setSelectedPaymentType(paymentType);
    setIsTransactionsModalOpen(true);
  };

  const handleCloseTransactionsModal = () => {
    setIsTransactionsModalOpen(false);
    setSelectedPaymentType(null);
  };

  const handleToggle = (ipg: IPGStatus, newStatus: boolean) => {
    updateStatus({
      ipg_type: ipg.ipg_type,
      is_active: newStatus,
    });
  };

  if (isLoading) {
    return (
      <PageContainer>
        <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
          <div>
            <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-56 mb-2 animate-pulse"></div>
            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-64 animate-pulse"></div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
          <div className="p-6">
            <div className="space-y-4">
              {[...Array(3)].map((_, i) => (
                <div
                  key={i}
                  className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg animate-pulse"
                >
                  <div className="flex-1">
                    <div className="flex items-center gap-3">
                      <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-32"></div>
                      <div className="h-5 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
                    </div>
                    <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-48 mt-2"></div>
                  </div>
                  <div className="h-6 w-11 bg-gray-200 dark:bg-gray-700 rounded-full"></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </PageContainer>
    );
  }

  if (error) {
    return (
      <PageContainer>
        <div className="text-center py-12">
          <p className="text-red-600 dark:text-red-400">
            خطا در بارگذاری وضعیت درگاه‌های پرداخت
          </p>
        </div>
      </PageContainer>
    );
  }

  const statuses = data?.statuses || [];

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

      <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div className="p-6">
          <div className="space-y-4">
            {statuses.map((ipg) => (
              <div
                key={ipg.ipg_type}
                className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
              >
                <div className="flex-1">
                  <div className="flex items-center gap-3">
                    <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
                      {IPG_LABELS[ipg.ipg_type]}
                    </h3>
                    <span
                      className={`px-2 py-1 rounded-md text-xs font-medium ${
                        ipg.is_active
                          ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200'
                          : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200'
                      }`}
                    >
                      {ipg.is_active ? 'فعال' : 'غیرفعال'}
                    </span>
                  </div>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    آخرین به‌روزرسانی: {formatDateTime(ipg.updated_at)}
                  </p>
                </div>
                <div className="flex items-center gap-4">
                  {isPending ? (
                    <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                  ) : (
                    <ToggleSwitch
                      checked={ipg.is_active}
                      onChange={(checked) => handleToggle(ipg, checked)}
                    />
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-6 space-y-6">
        {isPaymentReportLoading ? (
          <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
            <div className="text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری گزارش پرداخت‌ها...</div>
          </div>
        ) : paymentReportError ? (
          <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
            <p className="text-red-600 dark:text-red-400">خطا در دریافت گزارش پرداخت‌ها</p>
          </div>
        ) : paymentMethodsReport?.summary ? (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                    <CreditCard className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">کل تراکنش‌ها</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                      {formatWithThousands(paymentMethodsReport.summary.total_transactions)}
                    </p>
                  </div>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                    <CheckCircle className="h-5 w-5 text-green-600 dark:text-green-400" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">موفق</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                      {formatWithThousands(paymentMethodsReport.summary.successful_transactions)}
                    </p>
                  </div>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-red-100 dark:bg-red-900 rounded-lg">
                    <XCircle className="h-5 w-5 text-red-600 dark:text-red-400" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">ناموفق</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                      {formatWithThousands(paymentMethodsReport.summary.failed_transactions)}
                    </p>
                  </div>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                    <TrendingUp className="h-5 w-5 text-purple-600 dark:text-purple-400" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">نرخ موفقیت</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                      {formatWithThousands(paymentMethodsReport.summary.overall_success_rate.toFixed(2))}%
                    </p>
                  </div>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 md:col-span-2 lg:col-span-1">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-lg">
                    <DollarSign className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">مجموع مبلغ</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                      {formatCurrency(paymentMethodsReport.summary.total_amount)}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {paymentMethodsReport.summary.by_payment_type &&
              Object.keys(paymentMethodsReport.summary.by_payment_type).length > 0 && (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
                    آمار تفکیکی روش‌های پرداخت
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                    {Object.entries(paymentMethodsReport.summary.by_payment_type).map(([type, stats]) => (
                      <div
                        key={type}
                        className="border border-gray-200 dark:border-gray-700 rounded-lg p-4"
                      >
                        <div className="flex items-center justify-between mb-3">
                          <h4 className="font-semibold text-gray-900 dark:text-gray-100">
                            {getPaymentTypeLabel(type)}
                          </h4>
                          <button
                            onClick={() => handleOpenTransactionsModal(type)}
                            className="text-xs text-primary-600 hover:text-primary-700"
                          >
                            مشاهده تراکنش‌ها
                          </button>
                        </div>
                        <div className="space-y-2 text-sm">
                          <div className="flex justify-between">
                            <span className="text-gray-600 dark:text-gray-400">کل:</span>
                            <span className="font-medium">{formatWithThousands(stats.count)}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-600 dark:text-gray-400">موفق:</span>
                            <span className="font-medium text-green-600">
                              {formatWithThousands(stats.success_count)}
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-600 dark:text-gray-400">ناموفق:</span>
                            <span className="font-medium text-red-600">
                              {formatWithThousands(stats.failed_count)}
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-600 dark:text-gray-400">نرخ موفقیت:</span>
                            <span className="font-medium">
                              {formatWithThousands(stats.success_rate.toFixed(2))}%
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
          </>
        ) : null}
      </div>

      <Modal
        isOpen={isTransactionsModalOpen}
        onClose={handleCloseTransactionsModal}
        title={`تراکنش‌ها - ${selectedPaymentType ? getPaymentTypeLabel(selectedPaymentType) : ''}`}
        size="xl"
      >
        {isTransactionsLoading ? (
          <div className="text-sm text-gray-500 dark:text-gray-400">در حال بارگذاری تراکنش‌ها...</div>
        ) : paymentTransactionsError ? (
          <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
            <p className="text-red-600 dark:text-red-400">خطا در دریافت تراکنش‌ها</p>
          </div>
        ) : paymentTransactionsReport ? (
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">کل تراکنش‌ها</p>
                <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                  {formatWithThousands(paymentTransactionsReport.summary.total_transactions)}
                </p>
              </div>
              <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">موفق</p>
                <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                  {formatWithThousands(paymentTransactionsReport.summary.successful_count)}
                </p>
              </div>
              <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">ناموفق</p>
                <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                  {formatWithThousands(paymentTransactionsReport.summary.failed_count)}
                </p>
              </div>
              <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">میانگین مبلغ</p>
                <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                  {formatCurrency(paymentTransactionsReport.summary.average_transaction_amount)}
                </p>
              </div>
            </div>

            <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
              <Table columns={transactionColumns} data={transactionTableData} />
            </div>
          </div>
        ) : (
          <div className="text-sm text-gray-500 dark:text-gray-400">داده‌ای یافت نشد</div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default IPGListPage;







