import React, { useState } from 'react';
import { useShipmentsByMethodReport } from '../core/_hooks';
import { ShipmentsByMethodFilters } from '../core/_models';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
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, Truck, DollarSign, Package, Users, Clock, X } from 'lucide-react';
import { formatWithThousands, parseFormattedNumber, persianToEnglish } from '@/utils/numberUtils';

const formatCurrency = (amount: number) => {
  return formatWithThousands(amount) + ' تومان';
};

const formatDate = (dateString: string) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleDateString('fa-IR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
};

const formatWeight = (weight: number) => {
  return formatWithThousands(weight) + ' گرم';
};

const ShipmentsByMethodReportSkeleton = () => (
  <>
    {/* Summary Cards Skeleton */}
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
      {[...Array(8)].map((_, i) => (
        <div key={i} className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 animate-pulse">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-gray-200 dark:bg-gray-700 rounded-lg w-12 h-12"></div>
            <div className="flex-1">
              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
              <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
            </div>
          </div>
        </div>
      ))}
    </div>

    {/* Method Summaries Skeleton */}
    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 mb-6 animate-pulse">
      <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-48 mb-4"></div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[...Array(3)].map((_, i) => (
          <div key={i} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
            <div className="h-5 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
            <div className="space-y-1">
              {[...Array(6)].map((_, j) => (
                <div key={j} className="flex justify-between">
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20"></div>
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>

    {/* Table Skeleton */}
    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead className="bg-gray-50 dark:bg-gray-700">
            <tr>
              {[...Array(9)].map((_, i) => (
                <th key={i} className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded w-20"></div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            {[...Array(5)].map((_, i) => (
              <tr key={i} className="animate-pulse">
                {[...Array(9)].map((_, j) => (
                  <td key={j} className="px-6 py-4 whitespace-nowrap">
                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded"></div>
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </>
);

const ShipmentsByMethodReportPage = () => {
  const [filters, setFilters] = useState<ShipmentsByMethodFilters>({
    limit: 50,
    offset: 0,
    group_by_method: false,
  });

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

  const handleFilterChange = (key: keyof ShipmentsByMethodFilters, value: any) => {
    setFilters(prev => ({
      ...prev,
      [key]: value,
      offset: 0,
    }));
  };

  const handleDateRangeChange = (from: string | undefined, to: string | undefined) => {
    setFilters(prev => ({
      ...prev,
      date_range: {
        from,
        to,
      },
      offset: 0,
    }));
  };

  const handleNumericFilterChange = (key: 'shipping_method_id' | 'user_id' | 'min_shipping_cost' | 'max_shipping_cost', raw: string) => {
    const converted = persianToEnglish(raw).replace(/[^\d]/g, '');
    const numeric = converted ? Number(converted) : undefined;
    handleFilterChange(key, numeric);
  };

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

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

  const columns: TableColumn[] = [
    {
      key: 'order_number',
      label: 'شماره سفارش',
      align: 'right',
    },
    {
      key: 'customer_name',
      label: 'نام مشتری',
      align: 'right',
    },
    {
      key: 'customer_phone',
      label: 'شماره تماس',
      align: 'right',
    },
    {
      key: 'shipping_method',
      label: 'روش ارسال',
      align: 'right',
    },
    {
      key: 'shipping_cost',
      label: 'هزینه ارسال',
      align: 'right',
    },
    {
      key: 'order_amount',
      label: 'مبلغ سفارش',
      align: 'right',
    },
    {
      key: 'total_weight',
      label: 'وزن',
      align: 'right',
    },
    {
      key: 'status',
      label: 'وضعیت',
      align: 'right',
    },
    {
      key: 'payment_status',
      label: 'وضعیت پرداخت',
      align: 'right',
    },
    {
      key: 'created_at',
      label: 'زمان ثبت',
      align: 'right',
    },
  ];

  const tableData = (data?.shipments || []).map(shipment => ({
    order_number: shipment.order_number || '-',
    customer_name: shipment.customer_name || '-',
    customer_phone: shipment.customer_phone || '-',
    shipping_method: shipment.shipping_method || '-',
    shipping_cost: formatCurrency(shipment.shipping_cost),
    order_amount: formatCurrency(shipment.order_amount),
    total_weight: formatWeight(shipment.total_weight),
    status: shipment.status,
    payment_status: shipment.payment_status,
    created_at: formatDate(shipment.created_at),
  })) || [];

  const currentPage = Math.floor(filters.offset / filters.limit) + 1;
  const totalPages = data ? Math.ceil(data.total / filters.limit) : 1;

  return (
    <PageContainer>
      <PageTitle>گزارش ارسال‌ها بر اساس روش</PageTitle>

      {/* Filters */}
      <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>
          <Button
            variant="secondary"
            size="sm"
            onClick={handleClearFilters}
            className="flex items-center gap-2"
          >
            <X className="h-4 w-4" />
            پاک کردن فیلترها
          </Button>
        </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>
            <select
              value={filters.shipping_method_code || ''}
              onChange={(e) => handleFilterChange('shipping_method_code', e.target.value || undefined)}
              className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
            >
              <option value="">همه</option>
              <option value="express">پیک (اکسپرس)</option>
              <option value="standard">پست (معمولی)</option>
              <option value="pickup">تحویل حضوری</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              شناسه روش ارسال
            </label>
            <Input
              value={filters.shipping_method_id?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('shipping_method_id', e.target.value)}
              placeholder="مثلاً 1"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              شناسه کاربر
            </label>
            <Input
              value={filters.user_id?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('user_id', e.target.value)}
              placeholder="مثلاً 456"
              numeric
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              نام مشتری
            </label>
            <Input
              value={filters.customer_name || ''}
              onChange={(e) => handleFilterChange('customer_name', 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={filters.status || ''}
              onChange={(e) => handleFilterChange('status', e.target.value || undefined)}
              className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
            >
              <option value="">همه</option>
              <option value="pending">در انتظار</option>
              <option value="confirmed">تایید شده</option>
              <option value="processing">در حال پردازش</option>
              <option value="shipped">ارسال شده</option>
              <option value="delivered">تحویل داده شده</option>
              <option value="cancelled">لغو شده</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              وضعیت پرداخت
            </label>
            <select
              value={filters.payment_status || ''}
              onChange={(e) => handleFilterChange('payment_status', e.target.value || undefined)}
              className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
            >
              <option value="">همه</option>
              <option value="pending">در انتظار</option>
              <option value="paid">پرداخت شده</option>
              <option value="failed">ناموفق</option>
              <option value="refunded">مرجوع شده</option>
              <option value="cancelled">لغو شده</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداقل هزینه ارسال (ریال)
            </label>
            <Input
              value={filters.min_shipping_cost?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('min_shipping_cost', e.target.value)}
              placeholder="مثلاً 10000"
              numeric
              thousandSeparator
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              حداکثر هزینه ارسال (ریال)
            </label>
            <Input
              value={filters.max_shipping_cost?.toString() || ''}
              onChange={(e) => handleNumericFilterChange('max_shipping_cost', e.target.value)}
              placeholder="مثلاً 50000"
              numeric
              thousandSeparator
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              تاریخ شروع
            </label>
            <JalaliDateTimePicker
              value={filters.date_range?.from}
              onChange={(value) => handleDateRangeChange(value, filters.date_range?.to)}
              placeholder="انتخاب تاریخ شروع"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              تاریخ پایان
            </label>
            <JalaliDateTimePicker
              value={filters.date_range?.to}
              onChange={(value) => handleDateRangeChange(filters.date_range?.from, value)}
              placeholder="انتخاب تاریخ پایان"
            />
          </div>

          <div className="flex items-end">
            <label className="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
              <input
                type="checkbox"
                checked={filters.group_by_method || false}
                onChange={(e) => handleFilterChange('group_by_method', e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              گروه‌بندی بر اساس روش
            </label>
          </div>
        </div>
      </div>

      {/* Summary Cards */}
      {data?.summary && (
        <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">
                <Truck 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(data.summary.total_shipments)}
                </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.summary.total_shipping_cost)}
                </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">
                  {formatCurrency(data.summary.total_order_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-yellow-100 dark:bg-yellow-900 rounded-lg">
                <Clock 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.summary.average_shipping_cost)}
                </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-gray-100 dark:bg-gray-700 rounded-lg">
                <Clock className="h-5 w-5 text-gray-600 dark:text-gray-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.pending_shipments)}
                </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-blue-100 dark:bg-blue-900 rounded-lg">
                <Truck 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(data.summary.shipped_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-green-100 dark:bg-green-900 rounded-lg">
                <Package 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(data.summary.delivered_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-red-100 dark:bg-red-900 rounded-lg">
                <Package 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(data.summary.cancelled_count)}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Method Summaries */}
      {data?.method_summaries && data.method_summaries.length > 0 && (
        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4 mb-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 gap-4">
            {data.method_summaries.map((method) => (
              <div
                key={method.shipping_method_id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4"
              >
                <h4 className="font-semibold text-gray-900 dark:text-gray-100 mb-2">
                  {method.shipping_method || method.shipping_method_code}
                </h4>
                <div className="space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-600 dark:text-gray-400">تعداد ارسال:</span>
                    <span className="font-medium">{formatWithThousands(method.shipment_count)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600 dark:text-gray-400">مجموع درآمد:</span>
                    <span className="font-medium">{formatCurrency(method.total_revenue)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600 dark:text-gray-400">مجموع هزینه:</span>
                    <span className="font-medium">{formatCurrency(method.total_shipping_cost)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600 dark:text-gray-400">میانگین وزن:</span>
                    <span className="font-medium">{formatWeight(method.average_weight)}</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(method.delivered_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(method.cancelled_count)}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Table */}
      {isLoading ? (
        <ShipmentsByMethodReportSkeleton />
      ) : error ? (
        <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>
      ) : (
        <>
          <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
            <Table columns={columns} data={tableData} loading={isLoading} />
          </div>

          {data && data.total > 0 && totalPages > 1 && (
            <div className="mt-4 flex justify-center">
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                onPageChange={handlePageChange}
                itemsPerPage={filters.limit}
                totalItems={data.total}
              />
            </div>
          )}

          {data && data.total === 0 && (
            <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-8 text-center">
              <p className="text-gray-600 dark:text-gray-400">داده‌ای یافت نشد</p>
            </div>
          )}
        </>
      )}
    </PageContainer>
  );
};

export default ShipmentsByMethodReportPage;

