import React, { useState, useMemo } from 'react';
import { useVariantComparisonReport } from '../core/_hooks';
import { VariantComparisonFilters } from '../core/_models';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Table } from '@/components/ui/Table';
import { TableColumn } from '@/types';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { Pagination } from '@/components/ui/Pagination';
import { Filter, TrendingUp, TrendingDown, Package, DollarSign, X, Image as ImageIcon } from 'lucide-react';
import { formatWithThousands, parseFormattedNumber, persianToEnglish } from '@/utils/numberUtils';
import { formatCurrency } from '@/utils/formatters';
import { ReportSkeleton } from '@/components/common/ReportSkeleton';

const VariantComparisonReportPage = () => {
  const [filters, setFilters] = useState<VariantComparisonFilters>({
    limit: 50,
    offset: 0,
  });

  const [tempFilters, setTempFilters] = useState<VariantComparisonFilters>({
    limit: 50,
    offset: 0,
  });

  const { data, isLoading, error } = useVariantComparisonReport(filters);

  const handleTempFilterChange = (key: keyof VariantComparisonFilters, value: any) => {
    setTempFilters(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleApplyFilters = () => {
    setFilters({
      ...tempFilters,
      offset: 0,
    });
  };

  const handleClearFilters = () => {
    const clearedFilters = {
      limit: 50,
      offset: 0,
    };
    setTempFilters(clearedFilters);
    setFilters(clearedFilters);
  };

  const handleNumericFilterChange = (
    key: 'product_id' | 'min_stock' | 'max_stock' | 'min_fee_difference' | 'max_fee_difference',
    raw: string
  ) => {
    const converted = persianToEnglish(raw);
    const numeric = parseFormattedNumber(converted);
    handleTempFilterChange(key, numeric || undefined);
  };

  const handlePageChange = (page: number) => {
    setFilters(prev => ({
      ...prev,
      offset: (page - 1) * (prev.limit || 50),
    }));
  };

  const columns: TableColumn[] = useMemo(() => [
    {
      key: 'product_name',
      label: 'محصول',
      align: 'right',
      render: (_val, row: any) => (
        <div className="flex items-center gap-3">
          {row.image_url && (
            <img
              src={row.image_url}
              alt={row.product_name}
              className="w-10 h-10 object-cover rounded"
            />
          )}
          <div>
            <div className="font-medium">{row.product_name}</div>
            {row.product_sku && (
              <div className="text-xs text-gray-500 dark:text-gray-400">SKU: {row.product_sku}</div>
            )}
            {(row.variant_size || row.variant_color) && (
              <div className="text-xs text-gray-500 dark:text-gray-400">
                {row.variant_size && `سایز: ${row.variant_size}`}
                {row.variant_size && row.variant_color && ' - '}
                {row.variant_color && `رنگ: ${row.variant_color}`}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      key: 'weight',
      label: 'وزن (گرم)',
      align: 'right',
      render: (val: number) => formatWithThousands(val, 2),
    },
    {
      key: 'fee_percentage',
      label: 'درصد اجرت مشتری',
      align: 'right',
      render: (val: number) => `${formatWithThousands(val, 1)}%`,
    },
    {
      key: 'factory_fee_percentage',
      label: 'درصد اجرت کارخانه',
      align: 'right',
      render: (val: number) => `${formatWithThousands(val, 1)}%`,
    },
    {
      key: 'fee_difference',
      label: 'سود اجرت',
      align: 'right',
      render: (val: number) => (
        <span className={val >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}>
          {val >= 0 ? '+' : ''}{formatWithThousands(val, 1)}%
        </span>
      ),
    },
    {
      key: 'stock_number',
      label: 'موجودی',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
  ], []);

  const tableData = data?.variants || [];
  const limit = filters.limit || 50;
  const currentPage = Math.floor((filters.offset || 0) / limit) + 1;
  const totalPages = data?.total ? Math.ceil(data.total / limit) : 0;

  if (isLoading) {
    return (
      <PageContainer>
        <ReportSkeleton />
      </PageContainer>
    );
  }

  if (error) {
    return (
      <PageContainer>
        <div className="text-center py-12">
          <p className="text-gray-500 dark:text-gray-400">خطا در بارگذاری گزارش</p>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <PageTitle>گزارش مقایسه Variant‌ها</PageTitle>

      <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Filter className="h-5 w-5 text-gray-500" />
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">فیلترها</h3>
          </div>
          <div className="flex items-center gap-2">
            <Button
              onClick={handleApplyFilters}
              className="flex items-center gap-2"
            >
              <Filter className="h-4 w-4" />
              اعمال فیلترها
            </Button>
            <Button
              variant="secondary"
              size="sm"
              onClick={handleClearFilters}
              className="flex items-center gap-2"
            >
              <X className="h-4 w-4" />
              پاک کردن فیلترها
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              شناسه محصول
            </label>
            <Input
              value={tempFilters.product_id?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('product_id', e.target.value)}
              placeholder="مثلاً ۱۲۳"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              SKU محصول
            </label>
            <Input
              value={tempFilters.product_sku || ''}
              onChange={(e) => handleTempFilterChange('product_sku', e.target.value || undefined)}
              placeholder="مثلاً RING-001"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              رنگ Variant
            </label>
            <Input
              value={tempFilters.variant_color || ''}
              onChange={(e) => handleTempFilterChange('variant_color', e.target.value || undefined)}
              placeholder="مثلاً زرد"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              سایز Variant
            </label>
            <Input
              value={tempFilters.variant_size || ''}
              onChange={(e) => handleTempFilterChange('variant_size', e.target.value || undefined)}
              placeholder="مثلاً ۱۸"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              وضعیت فعال
            </label>
            <select
              value={tempFilters.enabled === undefined ? '' : tempFilters.enabled.toString()}
              onChange={(e) => handleTempFilterChange('enabled', e.target.value === '' ? undefined : e.target.value === 'true')}
              className="input"
            >
              <option value="">همه</option>
              <option value="true">فعال</option>
              <option value="false">غیرفعال</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداقل موجودی
            </label>
            <Input
              value={tempFilters.min_stock?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('min_stock', e.target.value)}
              placeholder="مثلاً ۵"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداکثر موجودی
            </label>
            <Input
              value={tempFilters.max_stock?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('max_stock', e.target.value)}
              placeholder="مثلاً ۱۰۰"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              فقط با موجودی
            </label>
            <select
              value={tempFilters.has_stock === undefined ? '' : tempFilters.has_stock.toString()}
              onChange={(e) => handleTempFilterChange('has_stock', e.target.value === '' ? undefined : e.target.value === 'true')}
              className="input"
            >
              <option value="">همه</option>
              <option value="true">بله</option>
              <option value="false">خیر</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداقل سود اجرت (%)
            </label>
            <Input
              value={tempFilters.min_fee_difference?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('min_fee_difference', e.target.value)}
              placeholder="مثلاً ۲.۵"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداکثر سود اجرت (%)
            </label>
            <Input
              value={tempFilters.max_fee_difference?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('max_fee_difference', e.target.value)}
              placeholder="مثلاً ۱۰"
              numeric
            />
          </div>
        </div>
      </div>

      {data && (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <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">
                  <Package 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">کل Variant‌ها</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                    {formatWithThousands(data.summary.total_variants)}
                  </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">
                  <TrendingUp 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">Variant‌های سودآور</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                    {formatWithThousands(data.summary.variants_with_higher_fee)}
                  </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">
                  <TrendingDown 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">Variant‌های زیان‌ده</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                    {formatWithThousands(data.summary.variants_with_lower_fee)}
                  </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-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">
                    {formatWithThousands(data.summary.average_fee_difference, 1)}%
                  </p>
                </div>
              </div>
            </div>
          </div>

          <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">
              لیست Variant‌ها
            </h3>
            <Table columns={columns} data={tableData} />
            {data && data.total !== undefined && data.total > 0 && totalPages > 1 && (
              <div className="mt-4">
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={handlePageChange}
                  itemsPerPage={limit}
                  totalItems={data.total}
                />
              </div>
            )}
          </div>
        </>
      )}
    </PageContainer>
  );
};

export default VariantComparisonReportPage;
