import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { api } from '../lib/api';
import { formatRial, rialToToman, tomanToRial } from '../lib/utils';

interface Pricing { free_visit_price_rials: number }

export default function FreeVisitPrice() {
  const qc = useQueryClient();
  const [value, setValue] = useState('');

  const { data } = useQuery<{ data: Pricing }>({
    queryKey: ['insurance-pricing'],
    queryFn: () => api.get('/api/v1/insurance-pricing'),
  });
  const pricing = (data as any)?.data as Pricing | undefined;

  useEffect(() => {
    if (pricing) setValue(String(rialToToman(pricing.free_visit_price_rials ?? 0)));
  }, [pricing]);

  const saveMut = useMutation({
    mutationFn: () => api.put('/api/v1/insurance-pricing', { free_visit_price_rials: tomanToRial(Number(value) || 0) }),
    onSuccess: () => {
      toast.success('قیمت ویزیت ذخیره شد');
      qc.invalidateQueries({ queryKey: ['insurance-pricing'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="card" style={{ padding: 20, marginBottom: 16 }}>
      <h2 style={{ fontSize: 14, fontWeight: 700, margin: '0 0 4px' }}>قیمت ویزیت آزاد</h2>
      <p style={{ fontSize: 12, color: 'var(--text-3)', margin: '0 0 12px', lineHeight: 1.7 }}>
        مبلغ ویزیت بدون بیمه. در ثبت مراجعه، انتخاب بیمه درصد پوشش قرارداد را روی همین مبلغ اعمال می‌کند.
      </p>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <label style={{ fontSize: 11.5, fontWeight: 600 }}>قیمت (تومان)</label>
          <input
            type="number" min={0} dir="ltr" className="input" style={{ width: 200 }}
            value={value} onChange={(e) => setValue(e.target.value)}
          />
        </div>
        <button className="btn primary sm" disabled={saveMut.isPending} onClick={() => saveMut.mutate()}>
          {saveMut.isPending ? '...' : 'ذخیره'}
        </button>
        {value !== '' && (
          <span style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 8 }}>{formatRial(tomanToRial(Number(value) || 0))}</span>
        )}
      </div>
    </div>
  );
}
