import React, { useState, useMemo } from 'react';
import { useInventoryValueReport } from '../core/_hooks';
import { Table } from '@/components/ui/Table';
import { TableColumn } from '@/types';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { Pagination } from '@/components/ui/Pagination';
import { DollarSign, Package, TrendingUp, Hash } from 'lucide-react';
import { formatWithThousands } from '@/utils/numberUtils';
import { formatCurrency } from '@/utils/formatters';
import { ReportSkeleton } from '@/components/common/ReportSkeleton';

const InventoryValueReportPage = () => {
  const { data, isLoading, error } = useInventoryValueReport();
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const columns: TableColumn[] = useMemo(() => [
    {
      key: 'factory_fee_percentage',
      label: 'درصد اجرت کارخانه',
      align: 'right',
      render: (val: number) => `${formatWithThousands(val, 1)}%`,
    },
    {
      key: 'raw_weight',
      label: 'وزن خام (گرم)',
      align: 'right',
      render: (val: number) => formatWithThousands(val, 2) + ' گرم',
    },
    {
      key: 'weight_with_fee',
      label: 'وزن با اجرت (گرم)',
      align: 'right',
      render: (val: number) => formatWithThousands(val, 2) + ' گرم',
    },
    {
      key: 'amount',
      label: 'ارزش (تومان)',
      align: 'right',
      render: (val: number) => formatCurrency(val),
    },
    {
      key: 'variants_count',
      label: 'تعداد Variant',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
    {
      key: 'stock_quantity',
      label: 'موجودی',
      align: 'right',
      render: (val: number) => formatWithThousands(val),
    },
  ], []);

  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>

      {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">
                  <DollarSign 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">
                    {formatCurrency(data.raw_inventory_amount)}
                  </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">
                  <DollarSign 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">
                    {formatCurrency(data.factory_fee_inventory_amount)}
                  </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">
                  <Package 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(data.raw_inventory_weight, 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">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-lg">
                  <TrendingUp 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(data.current_gold_price)}/گرم
                  </p>
                </div>
              </div>
            </div>
          </div>

          <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 border-gray-200 dark:border-gray-700 rounded-lg p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-indigo-100 dark:bg-indigo-900 rounded-lg">
                  <Hash className="h-5 w-5 text-indigo-600 dark:text-indigo-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.total_variants_count)}
                  </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-teal-100 dark:bg-teal-900 rounded-lg">
                  <Package className="h-5 w-5 text-teal-600 dark:text-teal-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.total_stock_quantity)}
                  </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">
              تفکیک بر اساس درصد اجرت کارخانه
            </h3>
            {(() => {
              const breakdownData = data.factory_fee_breakdown || [];
              const totalPages = Math.ceil(breakdownData.length / itemsPerPage);
              const startIndex = (currentPage - 1) * itemsPerPage;
              const endIndex = startIndex + itemsPerPage;
              const paginatedData = breakdownData.slice(startIndex, endIndex);
              
              return (
                <>
                  <Table columns={columns} data={paginatedData} />
                  {totalPages > 1 && (
                    <div className="mt-4">
                      <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={setCurrentPage}
                        itemsPerPage={itemsPerPage}
                        totalItems={breakdownData.length}
                      />
                    </div>
                  )}
                </>
              );
            })()}
          </div>
        </>
      )}
    </PageContainer>
  );
};

export default InventoryValueReportPage;
