import { useState } from 'react';
import { useParams, useNavigate } from 'react-router';
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import type { SessionCardData } from '../components/SessionServiceCard';
import SessionStepper from '../components/SessionStepper';
import PaymentStep from '../components/session/PaymentStep';
import DetailsStep from '../components/session/DetailsStep';
import { CloseModalD } from '../components/icons/FilesServiceIcons';
import { Breadcrumb } from '../components/PatientCaseBanner';
import TourButton from '../components/ui/TourButton';

/**
 * تکمیل پرداخت مراجعه — پورت صفحه‌ی tauri /files/create-service در حالت payment:
 * استپر دوگامی «پرداخت ← جزییات» با تخفیف تسویه، پرداخت چندتکه و تاریخ پرداخت.
 * بدنه‌ی گام‌ها در components/session/{PaymentStep,DetailsStep} مشترک با NewSessionPage است.
 */
export default function SessionPaymentPage() {
  const { recordUuid = '', sessionUuid = '' } = useParams();
  const nav = useNavigate();

  const steps = ['پرداخت', 'جزییات'];
  const [activeStep, setActiveStep] = useState(0);

  const recordQ = useQuery<ApiResponse<PatientRecord>>({
    queryKey: ['patient-detail', recordUuid],
    queryFn: () => api.get(`/api/v1/patient/${recordUuid}`),
    enabled: !!recordUuid,
  });
  const record = recordQ.data?.data as PatientRecord | undefined;
  const patientName = record?.user_name || record?.profile?.full_name || '—';

  const sessionsQ = useQuery<ApiResponse<SessionCardData[]>>({
    queryKey: ['patient-sessions', recordUuid],
    queryFn: () => api.get(`/api/v1/patient/${recordUuid}/sessions`),
    enabled: !!recordUuid,
  });
  const session = (sessionsQ.data?.data ?? []).find((s) => s.uuid === sessionUuid);

  const walletQ = useQuery<ApiResponse<{ balance_rials: number }>>({
    queryKey: ['patient-wallet', recordUuid],
    queryFn: () => api.get(`/api/v1/patient/${recordUuid}/wallet`),
    enabled: !!recordUuid,
  });
  const walletBalance = (walletQ.data?.data as any)?.balance_rials ?? 0;

  const finish = () => nav(`/admin/patients/${recordUuid}?tab=services`);

  if (sessionsQ.isLoading) {
    return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>در حال بارگذاری...</div>;
  }
  if (!session) {
    return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>مراجعه یافت نشد</div>;
  }

  return (
    <div className="fade-in" style={{ width: '100%' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }} data-tour="page-title">
        <Breadcrumb name={patientName} backTo={`/admin/patients/${recordUuid}`} />
        <TourButton tourId="session-payment" ready />
      </div>

      {/* card — tauri width 748 centered */}
      <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <div className="bg-[var(--surface)]" data-tour="session-card" style={{ width: 748, maxWidth: '100%', padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
            <button
              type="button"
              aria-label="بستن"
              onClick={() => nav(-1)}
              style={{ minWidth: 40, height: 40, marginBottom: 8, borderRadius: '50%', border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            >
              <CloseModalD />
            </button>
          </div>

          <SessionStepper activeStep={activeStep} steps={steps} />

          {activeStep === 0 ? (
            <PaymentStep
              recordUuid={recordUuid}
              session={session}
              walletBalance={walletBalance}
              onContinue={() => setActiveStep(1)}
              onCancel={() => nav(-1)}
            />
          ) : (
            <DetailsStep session={session} recordUuid={recordUuid} onBack={() => setActiveStep(0)} onFinish={finish} />
          )}
        </div>
      </div>
    </div>
  );
}
