import React, { useState, useMemo } from 'react';
import { useProfitLossReport } from '../core/_hooks';
import { ProfitLossFilters } 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 { JalaliDateTimePicker } from '@/components/ui/JalaliDateTimePicker';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { Pagination } from '@/components/ui/Pagination';
import { Filter, TrendingUp, TrendingDown, DollarSign, Package, X } from 'lucide-react';
import { formatWithThousands, parseFormattedNumber, persianToEnglish } from '@/utils/numberUtils';
import { formatCurrency } from '@/utils/formatters';
import { ReportSkeleton } from '@/components/common/ReportSkeleton';

const ProfitLossReportPage = () => {
  const [filters, setFilters] = useState<ProfitLossFilters>({});
  const [tempFilters, setTempFilters] = useState<ProfitLossFilters>({});
  const [productPage, setProductPage] = useState(1);
  const [categoryPage, setCategoryPage] = useState(1);
  const itemsPerPage = 10;

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

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

  const handleDateChange = (key: 'from' | 'to', value: string | undefined) => {
    handleTempFilterChange(key, value);
  };

  const handleNumericFilterChange = (
    key: 'min_profit_loss_grams' | 'max_profit_loss_grams' | 'min_profit_loss_tomans' | 'max_profit_loss_tomans',
    raw: string
  ) => {
    const converted = persianToEnglish(raw);
    const numeric = parseFormattedNumber(converted);
    handleTempFilterChange(key, numeric || undefined);
  };

  const handleApplyFilters = () => {
    setFilters(tempFilters);
    setProductPage(1);
    setCategoryPage(1);
  };

  const handleClearFilters = () => {
    const clearedFilters = {};
    setTempFilters(clearedFilters);
    setFilters(clearedFilters);
    setProductPage(1);
    setCategoryPage(1);
  };

  const productColumns: TableColumn[] = useMemo(() => [
    {
      key: 'product_name',
      label: 'نام محصول',
      align: 'right',
      render: (_val, row: any) => (
        <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>
          )}
        </div>
      ),
    },
    {
      key: 'profit_loss_grams',
      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, 2)} گرم
        </span>
      ),
    },
    {
      key: 'profit_loss_tomans',
      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 ? '+' : ''}{formatCurrency(val)}
        </span>
      ),
    },
    {
      key: 'total_quantity',
      label: 'تعداد فروش',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
    {
      key: 'order_items_count',
      label: 'تعداد آیتم‌ها',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
  ], []);

  const categoryColumns: TableColumn[] = useMemo(() => [
    {
      key: 'category_name',
      label: 'نام دسته‌بندی',
      align: 'right',
    },
    {
      key: 'profit_loss_grams',
      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, 2)} گرم
        </span>
      ),
    },
    {
      key: 'profit_loss_tomans',
      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 ? '+' : ''}{formatCurrency(val)}
        </span>
      ),
    },
    {
      key: 'total_quantity',
      label: 'تعداد فروش',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
    {
      key: 'products_count',
      label: 'تعداد محصولات',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
    {
      key: 'order_items_count',
      label: 'تعداد آیتم‌ها',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
  ], []);

  const profitLossData = data?.profit_loss;
  const isProfit = profitLossData ? profitLossData.profit_loss_grams >= 0 : false;

  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>گزارش سود و زیان</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>
            <JalaliDateTimePicker
              value={tempFilters.from}
              onChange={(value) => handleDateChange('from', value)}
              placeholder="انتخاب تاریخ شروع"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              تاریخ پایان
            </label>
            <JalaliDateTimePicker
              value={tempFilters.to}
              onChange={(value) => handleDateChange('to', value)}
              placeholder="انتخاب تاریخ پایان"
            />
          </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">
              نام دسته‌بندی
            </label>
            <Input
              value={tempFilters.category_name || ''}
              onChange={(e) => handleTempFilterChange('category_name', e.target.value || undefined)}
              placeholder="مثلاً ring"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداقل سود/زیان (گرم)
            </label>
            <Input
              value={tempFilters.min_profit_loss_grams?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('min_profit_loss_grams', 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_profit_loss_grams?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('max_profit_loss_grams', 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.min_profit_loss_tomans?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('min_profit_loss_tomans', 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_profit_loss_tomans?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('max_profit_loss_tomans', e.target.value)}
              placeholder="مثلاً ۵۰۰۰۰۰۰۰"
              numeric
            />
          </div>
        </div>
      </div>

      {profitLossData && (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div className={`bg-white dark:bg-gray-800 shadow-sm border-2 rounded-lg p-6 ${
              isProfit 
                ? 'border-green-500 dark:border-green-400' 
                : 'border-red-500 dark:border-red-400'
            }`}>
              <div className="flex items-center gap-3">
                <div className={`p-3 rounded-lg ${
                  isProfit 
                    ? 'bg-green-100 dark:bg-green-900' 
                    : 'bg-red-100 dark:bg-red-900'
                }`}>
                  {isProfit ? (
                    <TrendingUp className="h-6 w-6 text-green-600 dark:text-green-400" />
                  ) : (
                    <TrendingDown className="h-6 w-6 text-red-600 dark:text-red-400" />
                  )}
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">سود/زیان کل (گرم)</p>
                  <p className={`text-2xl font-bold ${
                    isProfit 
                      ? 'text-green-600 dark:text-green-400' 
                      : 'text-red-600 dark:text-red-400'
                  }`}>
                    {profitLossData.profit_loss_grams >= 0 ? '+' : ''}
                    {formatWithThousands(profitLossData.profit_loss_grams, 2)} گرم
                  </p>
                </div>
              </div>
            </div>

            <div className={`bg-white dark:bg-gray-800 shadow-sm border-2 rounded-lg p-6 ${
              isProfit 
                ? 'border-green-500 dark:border-green-400' 
                : 'border-red-500 dark:border-red-400'
            }`}>
              <div className="flex items-center gap-3">
                <div className={`p-3 rounded-lg ${
                  isProfit 
                    ? 'bg-green-100 dark:bg-green-900' 
                    : 'bg-red-100 dark:bg-red-900'
                }`}>
                  {isProfit ? (
                    <DollarSign className="h-6 w-6 text-green-600 dark:text-green-400" />
                  ) : (
                    <DollarSign className="h-6 w-6 text-red-600 dark:text-red-400" />
                  )}
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">سود/زیان کل (تومان)</p>
                  <p className={`text-2xl font-bold ${
                    isProfit 
                      ? 'text-green-600 dark:text-green-400' 
                      : 'text-red-600 dark:text-red-400'
                  }`}>
                    {profitLossData.profit_loss_tomans >= 0 ? '+' : ''}
                    {formatCurrency(profitLossData.profit_loss_tomans)}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <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>
              {(() => {
                const productData = profitLossData.product_breakdown || [];
                const productTotalPages = Math.ceil(productData.length / itemsPerPage);
                const productStartIndex = (productPage - 1) * itemsPerPage;
                const productEndIndex = productStartIndex + itemsPerPage;
                const paginatedProductData = productData.slice(productStartIndex, productEndIndex);
                
                return (
                  <>
                    <Table columns={productColumns} data={paginatedProductData} />
                    {productTotalPages > 1 && (
                      <div className="mt-4">
                        <Pagination
                          currentPage={productPage}
                          totalPages={productTotalPages}
                          onPageChange={setProductPage}
                          itemsPerPage={itemsPerPage}
                          totalItems={productData.length}
                        />
                      </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">
                تفکیک دسته‌بندی‌ها
              </h3>
              {(() => {
                const categoryData = profitLossData.category_breakdown || [];
                const categoryTotalPages = Math.ceil(categoryData.length / itemsPerPage);
                const categoryStartIndex = (categoryPage - 1) * itemsPerPage;
                const categoryEndIndex = categoryStartIndex + itemsPerPage;
                const paginatedCategoryData = categoryData.slice(categoryStartIndex, categoryEndIndex);
                
                return (
                  <>
                    <Table columns={categoryColumns} data={paginatedCategoryData} />
                    {categoryTotalPages > 1 && (
                      <div className="mt-4">
                        <Pagination
                          currentPage={categoryPage}
                          totalPages={categoryTotalPages}
                          onPageChange={setCategoryPage}
                          itemsPerPage={itemsPerPage}
                          totalItems={categoryData.length}
                        />
                      </div>
                    )}
                  </>
                );
              })()}
            </div>
          </div>
        </>
      )}
    </PageContainer>
  );
};

export default ProfitLossReportPage;
