import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, CheckIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Settlement } from '../types';
import { formatDate, formatRial } 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';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Modal from '../components/ui/Modal';

const STATUS_FILTERS = [
  { value: '', label: 'همه' },
  { value: 'pending', label: 'در انتظار' },
  { value: 'approved', label: 'تأیید شده' },
  { value: 'rejected', label: 'رد شده' },
];

export default function SettlementsPage() {
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState('pending');
  const [approveTarget, setApproveTarget] = useState<Settlement | null>(null);
  const [rejectTarget, setRejectTarget] = useState<Settlement | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const limit = 15;

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

  const approveMutation = useMutation({
    mutationFn: (s: Settlement) =>
      api.post<ApiResponse<null>>(`/api/v1/settlement/${s.uuid}/approve`, {}),
    onSuccess: () => {
      toast.success('تسویه تأیید شد');
      setApproveTarget(null);
      qc.invalidateQueries({ queryKey: ['settlements'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const rejectMutation = useMutation({
    mutationFn: ({ s, reason }: { s: Settlement; reason: string }) =>
      api.post<ApiResponse<null>>(`/api/v1/settlement/${s.uuid}/reject`, { reason }),
    onSuccess: () => {
      toast.success('تسویه رد شد');
      setRejectTarget(null);
      setRejectReason('');
      qc.invalidateQueries({ queryKey: ['settlements'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Settlement>[] = [
    { key: 'representation_name', header: 'نماینده', render: (s) => <span className="font-medium">{s.representation_name}</span> },
    { key: 'amount', header: 'مبلغ', render: (s) => formatRial(s.amount) },
    { key: 'bank_card', header: 'شماره کارت', render: (s) => s.bank_card ? <span dir="ltr" className="font-mono text-xs">{s.bank_card}</span> : '—' },
    { key: 'bank_name', header: 'بانک' },
    { key: 'status', header: 'وضعیت', render: (s) => <StatusBadge type="settlement" value={s.status} /> },
    { key: 'requested_at', header: 'تاریخ درخواست', render: (s) => formatDate(s.requested_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">
          {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<Settlement>
          columns={columns}
          data={items}
          loading={isLoading}
          emptyMessage="هیچ درخواست تسویه‌ای یافت نشد"
          actions={(s) => (
            <>
              <button onClick={() => navigate(`/admin/settlements/${s.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>
              {s.status === 'pending' && (
                <>
                  <button onClick={() => setApproveTarget(s)}
                    className="p-1.5 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors" title="تأیید">
                    <CheckIcon className="w-4 h-4" />
                  </button>
                  <button onClick={() => setRejectTarget(s)}
                    className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="رد">
                    <XMarkIcon className="w-4 h-4" />
                  </button>
                </>
              )}
            </>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

      <ConfirmDialog
        open={!!approveTarget}
        title="تأیید تسویه"
        message={`آیا از تأیید درخواست تسویه ${approveTarget?.representation_name} به مبلغ ${approveTarget ? formatRial(approveTarget.amount) : ''} اطمینان دارید؟`}
        confirmLabel="تأیید"
        loading={approveMutation.isPending}
        onConfirm={() => approveTarget && approveMutation.mutate(approveTarget)}
        onCancel={() => setApproveTarget(null)}
      />

      <Modal
        open={!!rejectTarget}
        title="رد درخواست تسویه"
        onClose={() => { setRejectTarget(null); setRejectReason(''); }}
        footer={
          <>
            <button onClick={() => { setRejectTarget(null); setRejectReason(''); }}
              className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
              لغو
            </button>
            <button
              onClick={() => rejectTarget && rejectMutation.mutate({ s: rejectTarget, reason: rejectReason })}
              disabled={!rejectReason || rejectMutation.isPending}
              className="px-4 py-2 bg-red-600 text-white text-sm rounded-[10px] hover:bg-red-700 disabled:opacity-50 transition-colors">
              {rejectMutation.isPending ? 'در حال ارسال...' : 'رد کردن'}
            </button>
          </>
        }
      >
        <label className="block text-sm font-medium text-gray-700 mb-2">دلیل رد:</label>
        <textarea
          value={rejectReason}
          onChange={(e) => setRejectReason(e.target.value)}
          rows={4}
          placeholder="دلیل رد درخواست را بنویسید..."
          className="w-full border border-gray-300 rounded-[10px] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
        />
      </Modal>
    </div>
  );
}
