import { useState } from 'react';
import { apiService, type EmailSubmissionData, type ApiResponse } from '../services/api';

export const useEmailSubmission = () => {
    const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
    const [message, setMessage] = useState<string>('');
    const [lastResponse, setLastResponse] = useState<ApiResponse | null>(null);

    /**
     * 提交邮件
     */
    const submitEmail = async (data: EmailSubmissionData): Promise<ApiResponse> => {
        if (!data.email) {
            const errorMessage = '请输入有效的邮箱地址';
            setStatus('error');
            setMessage(errorMessage);
            return { success: false, message: errorMessage };
        }

        // 基本邮箱验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(data.email)) {
            const errorMessage = '请输入有效的邮箱地址';
            setStatus('error');
            setMessage(errorMessage);
            return { success: false, message: errorMessage };
        }

        setStatus('loading');
        setMessage('');

        try {
            const response = await apiService.sendWelcomeEmail(data);

            setLastResponse(response);

            if (response.success) {
                setStatus('success');
                setMessage(response.message);

                // 如果提供了mailto链接，在新窗口打开（可选）
                if (response.data?.mailtoLink && import.meta.env.PROD) {
                    setTimeout(() => {
                        window.open(response.data.mailtoLink, '_blank');
                    }, 1000);
                }
            } else {
                setStatus('error');
                setMessage(response.message);
            }

            return response;
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '发送失败，请稍后重试';
            setStatus('error');
            setMessage(errorMessage);

            const errorResponse: ApiResponse = {
                success: false,
                message: errorMessage
            };
            setLastResponse(errorResponse);

            return errorResponse;
        }
    };

    /**
     * 重置状态
     */
    const reset = () => {
        setStatus('idle');
        setMessage('');
        setLastResponse(null);
    };

    /**
     * 检查是否有本地存储的待发送邮件
     */
    const hasPendingSubmissions = (): boolean => {
        const submissions = apiService.getLocalSubmissions();
        return submissions.some((sub: any) => sub.status === 'pending');
    };

    /**
     * 尝试重新发送待发送的邮件
     */
    const retryPendingSubmissions = async (): Promise<ApiResponse[]> => {
        return await apiService.retryPendingSubmissions();
    };

    return {
        status,
        message,
        lastResponse,
        submitEmail,
        reset,
        hasPendingSubmissions,
        retryPendingSubmissions,
        isLoading: status === 'loading',
        isSuccess: status === 'success',
        isError: status === 'error',
        isIdle: status === 'idle'
    };
};