import { Box, Button, Checkbox, Form, FormGroup, Panel, Textarea } from '@bigcommerce/big-design';
import { useEffect, useState } from 'react';

const Index = () => {
    const [adminEmails, setAdminEmails] = useState('');
    const [enableAdminNotifications, setEnableAdminNotifications] = useState(true);
    const [enableCustomerNotifications, setEnableCustomerNotifications] = useState(true);

    const [isLoading, setIsLoading] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);

    useEffect(() => {
        const load = async () => {
            setError(null);
            setSuccess(null);
            setIsLoading(true);

            try {
                const result = await fetch('/api/hose/notifications', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'get' }),
                }).then((r) => r.json());

                const settings = result?.settings;
                setAdminEmails(String(settings?.admin_emails ?? ''));
                setEnableAdminNotifications(Boolean(settings?.enable_admin_notifications ?? 0));
                setEnableCustomerNotifications(Boolean(settings?.enable_customer_notifications ?? 0));
            } catch (e: any) {
                const message = typeof e?.message === 'string' ? e.message : 'Failed to load settings';
                setError(message);
            } finally {
                setIsLoading(false);
            }
        };

        load();
    }, []);

    const save = async () => {
        setError(null);
        setSuccess(null);
        setIsSaving(true);

        try {
            const payload = {
                action: 'save',
                admin_emails: adminEmails,
                enable_admin_notifications: enableAdminNotifications,
                enable_customer_notifications: enableCustomerNotifications,
            };

            const result = await fetch('/api/hose/notifications', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
            }).then((r) => r.json());

            if (result?.message) {
                throw new Error(String(result.message));
            }

            setSuccess('Saved');
        } catch (e: any) {
            const message = typeof e?.message === 'string' ? e.message : 'Failed to save settings';
            setError(message);
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <Panel header="Notifications" description="Configure email notifications for storefront hose requests">
            <Box marginTop="large">
                <Form fullWidth={true} onSubmit={(e) => {
                    e.preventDefault();
                    save();
                }}>
                    <FormGroup>
                        <Textarea
                            label="Admin emails (comma-separated)"
                            placeholder="admin@example.com, ops@example.com"
                            value={adminEmails}
                            onChange={(e) => setAdminEmails(e.target.value)}
                            disabled={isLoading || isSaving}
                        />
                    </FormGroup>

                    <FormGroup>
                        <Checkbox
                            label="Enable admin notifications"
                            checked={enableAdminNotifications}
                            onChange={(e) => setEnableAdminNotifications(e.target.checked)}
                            disabled={isLoading || isSaving}
                        />
                    </FormGroup>

                    <FormGroup>
                        <Checkbox
                            label="Enable customer confirmation emails"
                            checked={enableCustomerNotifications}
                            onChange={(e) => setEnableCustomerNotifications(e.target.checked)}
                            disabled={isLoading || isSaving}
                        />
                    </FormGroup>

                    <Box>
                        <Button type="submit" isLoading={isSaving} disabled={isLoading || isSaving}>
                            Save
                        </Button>
                    </Box>

                    {error && (
                        <Box marginTop="medium" style={{ color: '#d14343' }}>
                            {error}
                        </Box>
                    )}

                    {success && (
                        <Box marginTop="medium" style={{ color: '#2d7a35' }}>
                            {success}
                        </Box>
                    )}
                </Form>
            </Box>
        </Panel>
    );
};

export default Index;
