import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon } from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { PaginatedResponse } from '../lib/api';
import type { Payment } from '../types';
import { formatDate, formatRial, maskMobile } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import StatusBadge from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';

const STATUS_FILTERS = [
  { value: '', label: 'همه' },
  { value: 'pending', label: 'در انتظار' },
  { value: 'received', label: 'موفق' },
  { value: 'canceled', label: 'لغو شده' },
  { value: 'refund', label: 'استرداد' },
];

export default function PaymentsPage() {
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['payments', page, search, statusFilter],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      if (statusFilter) params.set('status', statusFilter);
      return api.get<PaginatedResponse<Payment>>(`/api/v1/admin/payments?${params}`);
    },
  });

  const columns: Column<Payment>[] = [
    {
      key: 'patient_mobile',
      header: 'موبایل',
      render: (p) => <span dir="ltr">{maskMobile(p.patient_mobile)}</span>,
    },
    {
      key: 'amount',
      header: 'مبلغ',
      render: (p) => <span className="font-medium">{formatRial(p.amount)}</span>,
    },
    {
      key: 'status',
      header: 'وضعیت',
      render: (p) => <StatusBadge type="payment" value={p.status} />,
    },
    {
      key: 'gateway',
      header: 'درگاه',
      render: (p) => (
        <span className="text-xs bg-gray-100 text-gray-700 px-2 py-0.5 rounded-full uppercase">
          {p.gateway}
        </span>
      ),
    },
    {
      key: 'ref_id',
      header: 'شماره مرجع',
      render: (p) => p.ref_id ? <span dir="ltr" className="font-mono text-xs">{p.ref_id}</span> : '—',
    },
    {
      key: 'paid_at',
      header: 'تاریخ پرداخت',
      render: (p) => formatDate(p.paid_at),
    },
    {
      key: 'created_at',
      header: 'تاریخ ثبت',
      render: (p) => formatDate(p.created_at),
    },
  ];

  const items = data?.data ?? [];
  const total = data?.meta?.totalRecords ?? 0;

  return (
    <div>
      <PageHeader
        title="پرداخت‌ها"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'پرداخت‌ها' }]}
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <div className="flex items-center gap-3 mb-4 flex-wrap">
          {STATUS_FILTERS.map((f) => (
            <button key={f.value} onClick={() => { setStatusFilter(f.value); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                statusFilter === f.value
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}>
              {f.label}
            </button>
          ))}
        </div>

        <DataTable<Payment>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس موبایل یا شماره مرجع..."
          emptyMessage="هیچ پرداختی یافت نشد"
          actions={(payment) => (
            <button onClick={() => navigate(`/admin/payments/${payment.uuid}`)}
              className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors" title="مشاهده">
              <EyeIcon className="w-4 h-4" />
            </button>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>
    </div>
  );
}
