import React, { useState } from 'react';
import { useProductComments, useUpdateCommentStatus, useDeleteComment } from '../core/_hooks';
import { ProductCommentFilters, CommentStatus } 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 { Modal } from '@/components/ui/Modal';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { Pagination } from '@/components/ui/Pagination';
import { Filter, CheckCircle, XCircle, Trash2, MessageSquare, Star } from 'lucide-react';
import { formatWithThousands, persianToEnglish } from '@/utils/numberUtils';
import { formatDateTime } from '@/utils/formatters';

const getStatusColor = (status: CommentStatus) => {
  const colors = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    approved: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    rejected: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
  };
  return colors[status] || colors.pending;
};

const getStatusText = (status: CommentStatus) => {
  const text = {
    pending: 'در انتظار',
    approved: 'تایید شده',
    rejected: 'رد شده',
  };
  return text[status] || status;
};

const ProductCommentsListPage = () => {
  const [filters, setFilters] = useState<ProductCommentFilters>({
    limit: 20,
    offset: 0,
  });

  const [statusUpdateId, setStatusUpdateId] = useState<number | null>(null);
  const [newStatus, setNewStatus] = useState<'approved' | 'rejected'>('approved');
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const { data, isLoading, error } = useProductComments(filters);
  const { mutate: updateStatus, isPending: isUpdating } = useUpdateCommentStatus();
  const { mutate: deleteComment, isPending: isDeleting } = useDeleteComment();

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

  const handleNumericFilterChange = (key: 'productId' | 'userId', 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 handleStatusUpdate = () => {
    if (statusUpdateId === null) return;
    updateStatus(
      { commentId: statusUpdateId.toString(), payload: { status: newStatus } },
      {
        onSuccess: () => {
          setStatusUpdateId(null);
        },
      }
    );
  };

  const handleDeleteConfirm = () => {
    if (deleteId === null) return;
    deleteComment(deleteId.toString(), {
      onSuccess: () => {
        setDeleteId(null);
      },
    });
  };

  const columns: TableColumn[] = [
    {
      key: 'user_name',
      label: 'کاربر',
      align: 'right',
    },
    {
      key: 'product_id',
      label: 'شناسه محصول',
      align: 'right',
    },
    {
      key: 'rating',
      label: 'امتیاز',
      align: 'right',
      render: (_val, row) => '⭐'.repeat(row.rating) + ` (${row.rating})`,
    },
    {
      key: 'subject',
      label: 'موضوع',
      align: 'right',
    },
    {
      key: 'comment',
      label: 'نظر',
      align: 'right',
      render: (_val, row) => row.comment.length > 50
        ? row.comment.substring(0, 50) + '...'
        : row.comment,
    },
    {
      key: 'comment_status',
      label: 'وضعیت',
      align: 'right',
      render: (_val, row) => (
        <span className={`px-2 py-1 rounded text-xs font-medium ${getStatusColor(row.comment_status)}`}>
          {getStatusText(row.comment_status)}
        </span>
      ),
    },
    {
      key: 'created_at',
      label: 'تاریخ ایجاد',
      align: 'right',
      render: (val) => formatDateTime(val),
    },
    {
      key: 'actions',
      label: 'عملیات',
      align: 'center',
      render: (_val, row) => (
        <div className="flex items-center justify-center gap-2">
          {row.comment_status === 'pending' && (
            <>
              <button
                onClick={() => {
                  setStatusUpdateId(row.id);
                  setNewStatus('approved');
                }}
                className="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300 p-1"
                title="تایید"
              >
                <CheckCircle className="h-4 w-4" />
              </button>
              <button
                onClick={() => {
                  setStatusUpdateId(row.id);
                  setNewStatus('rejected');
                }}
                className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 p-1"
                title="رد"
              >
                <XCircle className="h-4 w-4" />
              </button>
            </>
          )}
          <button
            onClick={() => setDeleteId(row.id)}
            className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 p-1"
            title="حذف"
          >
            <Trash2 className="h-4 w-4" />
          </button>
        </div>
      ),
    },
  ];

  const tableData = (data?.comments || []).map(comment => ({
    id: comment.id,
    user_name: comment.user
      ? `${comment.user.first_name} ${comment.user.last_name}`.trim() || '-'
      : '-',
    product_id: formatWithThousands(comment.product_id),
    rating: comment.rating,
    subject: comment.subject || '-',
    comment: comment.comment,
    comment_status: comment.comment_status,
    created_at: comment.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 gap-2 mb-4">
          <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="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.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="approved">تایید شده</option>
              <option value="rejected">رد شده</option>
            </select>
          </div>

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

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

      {/* Table */}
      {isLoading ? (
        <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={[]} loading={true} />
        </div>
      ) : 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">
              <MessageSquare className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600 dark:text-gray-400">نظری یافت نشد</p>
            </div>
          )}
        </>
      )}

      {/* Status Update Modal */}
      <Modal
        isOpen={statusUpdateId !== null}
        onClose={() => setStatusUpdateId(null)}
        title="تغییر وضعیت نظر"
      >
        <div className="space-y-4">
          <p className="text-gray-700 dark:text-gray-300">
            آیا می‌خواهید وضعیت این نظر را به{' '}
            <span className="font-semibold">
              {newStatus === 'approved' ? 'تایید شده' : 'رد شده'}
            </span>{' '}
            تغییر دهید؟
          </p>
          <div className="flex justify-end gap-2">
            <Button
              variant="secondary"
              onClick={() => setStatusUpdateId(null)}
            >
              انصراف
            </Button>
            <Button
              onClick={handleStatusUpdate}
              loading={isUpdating}
              variant={newStatus === 'approved' ? 'success' : 'danger'}
            >
              تایید
            </Button>
          </div>
        </div>
      </Modal>

      {/* Delete Modal */}
      <Modal
        isOpen={deleteId !== null}
        onClose={() => setDeleteId(null)}
        title="حذف نظر"
      >
        <div className="space-y-4">
          <p className="text-gray-700 dark:text-gray-300">
            آیا از حذف این نظر اطمینان دارید؟ این عمل قابل بازگشت نیست.
          </p>
          <div className="flex justify-end gap-2">
            <Button
              variant="secondary"
              onClick={() => setDeleteId(null)}
            >
              انصراف
            </Button>
            <Button
              variant="danger"
              onClick={handleDeleteConfirm}
              loading={isDeleting}
            >
              حذف
            </Button>
          </div>
        </div>
      </Modal>
    </PageContainer>
  );
};

export default ProductCommentsListPage;

