'use client';

import { useEffect, useState } from 'react';
import { App, Input, Modal } from 'antd';
import { api, errMsg } from '@/lib/api';

export type RiskUser = {
  id: number;
  phone: string;
  is_high_risk: boolean;
  high_risk_note: string | null;
};

type Props = {
  user: RiskUser | null;
  open: boolean;
  onClose: () => void;
  onDone: () => void | Promise<void>;
};

export function UserRiskModal({ user, open, onClose, onDone }: Props) {
  const { message } = App.useApp();
  const [note, setNote] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (open) setNote(user?.high_risk_note ?? '');
  }, [open, user]);

  const save = async () => {
    if (!user) return;
    const trimmed = note.trim();
    if (!trimmed) {
      message.warning('请输入标记为高风险的原因');
      return;
    }
    setSaving(true);
    try {
      await api.post(`/admin/api/users/${user.id}/risk`, {
        is_high_risk: true,
        note: trimmed,
      });
      message.success(user.is_high_risk ? '高风险备注已更新' : '已标记为高风险');
      await onDone();
      onClose();
    } catch (error) {
      message.error(errMsg(error));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      title="高风险备注"
      open={open}
      okText="保存"
      confirmLoading={saving}
      onOk={save}
      onCancel={onClose}
      destroyOnHidden
    >
      <Input.TextArea
        autoFocus
        rows={5}
        maxLength={500}
        showCount
        value={note}
        placeholder="请输入标记为高风险的原因"
        onChange={(event) => setNote(event.target.value)}
      />
    </Modal>
  );
}

export async function clearUserRisk(userId: number) {
  await api.post(`/admin/api/users/${userId}/risk`, {
    is_high_risk: false,
    note: null,
  });
}
