import React, { useState } from 'react';
import { toast } from 'sonner';
import SettingsLayout from '../components/layout/SettingsLayout';
import PageHeader from '../components/ui/PageHeader';
import PaymentMethodHead, { type PaymentTab } from '../components/paymentMethods/PaymentMethodHead';
import BankAccountTable from '../components/paymentMethods/BankAccountTable';
import PosTable from '../components/paymentMethods/PosTable';
import BankAccountFormModal from '../components/paymentMethods/BankAccountFormModal';
import PosFormModal from '../components/paymentMethods/PosFormModal';
import {
  useBankAccounts,
  usePosDevices,
  useToggleBankAccountStatus,
  useTogglePosStatus,
  type BankAccount,
  type Pos,
} from '../hooks/usePaymentMethods';

/**
 * صفحهٔ «مدیریت پرداخت» (/admin/my-financial) — پورت تب PaymentManagement از
 * clinic-pro-tauri. روش‌های پرداختِ کلینیک (حساب بانکی + کارت‌خوان) که بعداً از
 * فاکتور مراجعه‌کننده برای ثبت روش پرداخت یک سرویس ارجاع می‌شوند.
 */
function MyFinancialPageContent() {
  const [activeTab, setActiveTab] = useState<PaymentTab>('bank');
  const [bankModalOpen, setBankModalOpen] = useState(false);
  const [posModalOpen, setPosModalOpen] = useState(false);
  const [editingBank, setEditingBank] = useState<BankAccount | null>(null);
  const [editingPos, setEditingPos] = useState<Pos | null>(null);

  const bankQuery = useBankAccounts();
  const posQuery = usePosDevices();
  const toggleBank = useToggleBankAccountStatus();
  const togglePos = useTogglePosStatus();

  const banks = bankQuery.data?.data ?? [];
  const posDevices = posQuery.data?.data ?? [];

  const openAdd = () => {
    if (activeTab === 'bank') { setEditingBank(null); setBankModalOpen(true); }
    else { setEditingPos(null); setPosModalOpen(true); }
  };

  const onError = (e: unknown) => toast.error(e instanceof Error ? e.message : 'خطا در تغییر وضعیت');

  return (
    <div className="page">
      <PageHeader title="مدیریت پرداخت" description="روش‌های پرداخت کلینیک (حساب بانکی و کارت‌خوان)" />

      <div className="card card-pad">
        <PaymentMethodHead activeTab={activeTab} onTabChange={setActiveTab} onAdd={openAdd} />

        {activeTab === 'bank' ? (
          <BankAccountTable
            data={banks}
            loading={bankQuery.isLoading}
            togglingUuid={toggleBank.isPending ? toggleBank.variables ?? null : null}
            onToggle={(uuid) => toggleBank.mutate(uuid, { onError })}
            onEdit={(account) => { setEditingBank(account); setBankModalOpen(true); }}
            onAdd={openAdd}
          />
        ) : (
          <PosTable
            data={posDevices}
            loading={posQuery.isLoading}
            togglingUuid={togglePos.isPending ? togglePos.variables ?? null : null}
            onToggle={(uuid) => togglePos.mutate(uuid, { onError })}
            onEdit={(pos) => { setEditingPos(pos); setPosModalOpen(true); }}
            onAdd={openAdd}
          />
        )}
      </div>

      <BankAccountFormModal
        open={bankModalOpen}
        account={editingBank}
        onClose={() => { setBankModalOpen(false); setEditingBank(null); }}
      />
      <PosFormModal
        open={posModalOpen}
        pos={editingPos}
        onClose={() => { setPosModalOpen(false); setEditingPos(null); }}
      />
    </div>
  );
}

export default function MyFinancialPage() {
  return (
    <SettingsLayout active="payment">
      <MyFinancialPageContent />
    </SettingsLayout>
  );
}
