import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  MagnifyingGlassIcon, EyeIcon,
  BanknotesIcon, ClockIcon, CreditCardIcon, ArrowDownTrayIcon,
} 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 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: 'success', label: 'موفق' },
  { value: 'failed', label: 'ناموفق' },
  { value: 'canceled', label: 'لغو شده' },
  { value: 'refunded', 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) => (
        <div className="cell-user">
          <div className="avatar sm" style={{
            background: `linear-gradient(145deg, oklch(0.62 0.15 162), oklch(0.48 0.16 162))`,
          }}>
            {maskMobile(p.patient_mobile).slice(0, 2)}
          </div>
          <span dir="ltr">{maskMobile(p.patient_mobile)}</span>
        </div>
      ),
    },
    {
      key: 'amount',
      header: 'مبلغ',
      render: (p) => <b>{formatRial(p.amount)}</b>,
    },
    {
      key: 'status',
      header: 'وضعیت',
      render: (p) => <StatusBadge type="payment" value={p.status} />,
    },
    {
      key: 'gateway',
      header: 'درگاه',
      render: (p) => <span className="chip" style={{ fontSize: 12 }}>{p.gateway}</span>,
    },
    {
      key: 'ref_id',
      header: 'شماره مرجع',
      render: (p) => p.ref_id
        ? <span dir="ltr" style={{ fontFamily: 'monospace', fontSize: 12.5, color: 'var(--text-2)' }}>{p.ref_id}</span>
        : <span className="muted">—</span>,
    },
    {
      key: 'paid_at',
      header: 'تاریخ پرداخت',
      render: (p) => <span className="muted">{formatDate(p.paid_at)}</span>,
    },
    {
      key: 'created_at',
      header: 'تاریخ ثبت',
      render: (p) => <span className="muted">{formatDate(p.created_at)}</span>,
    },
  ];

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

  const statCards = [
    { label: 'کل تراکنش‌ها',  value: total > 0 ? String(total) : null, bg: 'var(--primary-soft)',  color: 'var(--primary)',   Icon: CreditCardIcon },
    { label: 'تأییدشده',       value: null,                              bg: 'var(--success-bg)',    color: 'var(--success)',   Icon: BanknotesIcon },
    { label: 'در انتظار',      value: null,                              bg: 'var(--warning-bg)',    color: 'var(--warning)',   Icon: ClockIcon },
    { label: 'استرداد شده',    value: null,                              bg: 'var(--info-bg)',       color: 'var(--info)',      Icon: ArrowDownTrayIcon },
  ];

  return (
    <div className="fade-in">
      {/* Header */}
      <div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
        <div>
          <h1 className="section-title">پرداخت‌ها</h1>
          <div className="muted" style={{ fontSize: 13, marginTop: 3 }}>مدیریت تراکنش‌های مالی</div>
        </div>
        <button className="btn ghost sm">
          <ArrowDownTrayIcon style={{ width: 15, height: 15 }} />
          خروجی اکسل
        </button>
      </div>

      {/* Stat cards */}
      <div className="stat-grid">
        {statCards.map((c) => (
          <div key={c.label} className="stat">
            <div className="ico" style={{ background: c.bg, color: c.color }}>
              <c.Icon style={{ width: 20, height: 20 }} />
            </div>
            <div className="lbl">{c.label}</div>
            <div className="val">
              {isLoading
                ? <span className="skeleton" style={{ display: 'inline-block', width: 48, height: 26, borderRadius: 4 }} />
                : c.value ?? '—'}
            </div>
          </div>
        ))}
      </div>

      {/* Main card */}
      <div className="card">
        <div className="card-pad" style={{ paddingBottom: 0 }}>
          <div className="toolbar">
            <div className="field" style={{ minWidth: 240 }}>
              <MagnifyingGlassIcon style={{ width: 17, height: 17 }} />
              <input
                placeholder="جستجو بر اساس موبایل یا شماره مرجع..."
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              />
            </div>
            <div className="seg">
              {STATUS_FILTERS.map((f) => (
                <button
                  key={f.value}
                  className={statusFilter === f.value ? 'on' : ''}
                  onClick={() => { setStatusFilter(f.value); setPage(1); }}
                >
                  {f.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        <DataTable<Payment>
          columns={columns}
          data={items}
          loading={isLoading}
          emptyMessage="هیچ پرداختی یافت نشد"
          actions={(payment) => (
            <button
              className="mini-btn"
              onClick={() => navigate(`/admin/payments/${payment.uuid}`)}
              title="مشاهده"
            >
              <EyeIcon style={{ width: 16, height: 16 }} />
            </button>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>
    </div>
  );
}
