import React, { useState, useEffect } from "react";
import { FiArrowLeft, FiInfo, FiSave } from 'react-icons/fi';
import styles from '../../chatbot/components/ChatbotSettings.module.css';
import { useGetReportsSettings, useUpdateReportsSettings } from "app/utils/api";
import { useToast } from "app/components/providers/use-toast";

interface ReportsSettingsProps {
    onBack: () => void;
}

export function ReportsSettings({ onBack }: ReportsSettingsProps) {
    const { data: response, isLoading } = useGetReportsSettings();
    const updateMutation = useUpdateReportsSettings();
    const { showSuccess, showError } = useToast();
    const [formData, setFormData] = useState<any>(null);

    const defaultData = {
        app_performance_report: { enabled: true, bcc_emails: [] },
        unresolved_questions_reminder: { enabled: true, bcc_emails: [] }
    };

    useEffect(() => {
        if (response?.data) {
            setFormData({ ...defaultData, ...response.data });
        } else if (!isLoading) {
            setFormData(defaultData);
        }
    }, [response, isLoading]);

    const handleSave = async () => {
        try {
            await updateMutation.mutateAsync(formData);
            showSuccess("Report settings updated successfully");
        } catch (err) {
            showError("Failed to update report settings");
        }
    };

    if (isLoading || !formData) return <div style={{ padding: '24px' }}>Loading reports settings...</div>;

    const updateNested = (category: string, field: string, value: any) => {
        setFormData((prev: any) => ({
            ...prev,
            [category]: {
                ...prev[category],
                [field]: value
            }
        }));
    };

    return (
        <div className={styles.settingsLayout}>
            <div className={styles.settingsFlexHeader} style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <button
                        onClick={onBack}
                        style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', fontSize: '20px' }}
                    >
                        <FiArrowLeft />
                    </button>
                    <h1 className={styles.faqTitle} style={{ fontSize: '22px', margin: 0 }}>Reports</h1>
                </div>
                <button
                    className={styles.syncBtn}
                    style={{ background: '#7c3aed', gap: '8px', display: 'flex', alignItems: 'center' }}
                    onClick={handleSave}
                    disabled={updateMutation.isPending}
                >
                    <FiSave /> {updateMutation.isPending ? 'Saving...' : 'Save changes'}
                </button>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                {/* App performance report */}
                <div className={styles.appearanceCard}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px', flexWrap: 'wrap', gap: '12px' }}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600 }}>App performance report</h3>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={formData.app_performance_report?.enabled}
                                onChange={(e) => updateNested('app_performance_report', 'enabled', e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                    <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '24px' }}>{formData.app_performance_report?.description || "Get weekly report on key metrics and performance trends."}</p>

                    <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                            <label style={{ fontSize: '13px', color: '#374151', fontWeight: 500 }}>BCC</label>
                            <FiInfo size={14} color="#9ca3af" />
                        </div>
                        <input
                            type="text"
                            className={styles.chatInput}
                            placeholder="Email addresses separated by commas"
                            style={{ width: '100%', textAlign: 'left', background: '#f9fafb', height: '44px', padding: '0 16px' }}
                            value={formData.app_performance_report?.bcc_emails?.join(', ') || ""}
                            onChange={(e) => updateNested('app_performance_report', 'bcc_emails', e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean))}
                        />
                    </div>
                </div>

                {/* Unresolved questions reminder */}
                <div className={styles.appearanceCard}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px', flexWrap: 'wrap', gap: '12px' }}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Unresolved questions reminder</h3>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={formData.unresolved_questions_reminder?.enabled}
                                onChange={(e) => updateNested('unresolved_questions_reminder', 'enabled', e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                    <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '24px' }}>
                        {formData.unresolved_questions_reminder?.description || "Get weekly email reminder if there are more than 10 unresolved questions."} <span style={{ color: '#7c3aed', cursor: 'pointer' }} onClick={() => window.open(formData.unresolved_questions_reminder?.review_link || "#", "_blank")}>Review unresolved questions</span>
                    </p>

                    <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                            <label style={{ fontSize: '13px', color: '#374151', fontWeight: 500 }}>BCC</label>
                            <FiInfo size={14} color="#9ca3af" />
                        </div>
                        <input
                            type="text"
                            className={styles.chatInput}
                            placeholder="Email addresses separated by commas"
                            style={{ width: '100%', textAlign: 'left', background: '#f9fafb', height: '44px', padding: '0 16px' }}
                            value={formData.unresolved_questions_reminder?.bcc_emails?.join(', ') || ""}
                            onChange={(e) => updateNested('unresolved_questions_reminder', 'bcc_emails', e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean))}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
}
