'use client';

import { LayoutShell } from '../../../../components/layout-shell';
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { Lock, Mail, Bell, Save, Eye, EyeOff, RefreshCw } from 'lucide-react';

export default function SettingsPage() {
    const queryClient = useQueryClient();
    const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

    const OVERAGE_KEY = 'allow_over_expected_delivery_quantity';
    const MAINTENANCE_KEY = 'maintenance_mode';
    
    // Local state for form inputs
    const [formState, setFormState] = useState<Record<string, string>>({});
    const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({});

    // Fetch existing settings
    const { data: settingsData, isLoading } = useQuery({
        queryKey: ['system-settings'],
        queryFn: async () => {
            const res = await api.get('/admin/settings');
            return res.data.data;
        }
    });

    // Initialize form state when data loads
    useEffect(() => {
        if (settingsData) {
            const initial: Record<string, string> = {};
            Object.values(settingsData).forEach((setting: any) => {
                // We store the masked value initially
                initial[setting.key] = setting.value || '';
            });

            // Ensure our feature toggle exists in local form state even if not yet set in DB
            if (initial[OVERAGE_KEY] === undefined) {
                initial[OVERAGE_KEY] = '0';
            }
            if (initial[MAINTENANCE_KEY] === undefined) {
                initial[MAINTENANCE_KEY] = '0';
            }
            setFormState(initial);
        }
    }, [settingsData]);

    const updateSettings = useMutation({
        mutationFn: async (updates: Record<string, string>) => {
            await api.post('/admin/settings', { settings: updates });
        },
        onSuccess: () => {
            setMessage({ type: 'success', text: 'Settings updated successfully' });
            queryClient.invalidateQueries({ queryKey: ['system-settings'] });
            setTimeout(() => setMessage(null), 3000);
        },
        onError: (err: any) => {
            setMessage({ type: 'error', text: err.response?.data?.error || 'Failed to update settings' });
        }
    });

    const runQaFix = useMutation({
        mutationFn: async () => {
            const res = await api.post('/admin/qa/remaining-quantities');
            return res.data;
        },
        onSuccess: (data) => {
            const checked = data?.checked ?? 0;
            const fixed = data?.fixed ?? 0;
            const details = [
                `Null->planned: ${data?.null_remaining_fixed ?? 0}`,
                `Clamped low: ${data?.clamped_low ?? 0}`,
                `Clamped high: ${data?.clamped_high ?? 0}`,
                `Flagged over-expected: ${data?.flagged_over_expected ?? 0}`,
                `Flagged future: ${data?.flagged_future_date ?? 0}`,
                `Flagged duplicates: ${data?.flagged_duplicates ?? 0}`,
            ].join(' | ');
            setMessage({ type: 'success', text: `QA completed. Checked ${checked} plans, fixed ${fixed}. ${details}` });
            setTimeout(() => setMessage(null), 4000);
        },
        onError: (err: any) => {
            setMessage({ type: 'error', text: err.response?.data?.error || 'QA run failed' });
        }
    });

    const handleSave = () => {
        const updates: Record<string, string> = {};
        
        // Only send values that have changed from the masked version
        // OR if it's a new value (not masked)
        Object.entries(formState).forEach(([key, value]) => {
            const original = settingsData?.[key]?.value;
            // If value is different from original (masked) value, it means user typed something new
            // If original was null/empty and now has value, send it
            if (value !== original) {
                updates[key] = value;
            }
        });

        if (Object.keys(updates).length === 0) {
            setMessage({ type: 'success', text: 'No changes to save' });
            return;
        }

        updateSettings.mutate(updates);
    };

    const toggleShow = (key: string) => {
        setShowSecrets(prev => ({ ...prev, [key]: !prev[key] }));
    };

    return (
        <LayoutShell role="SUPER_ADMIN">
            <div className="max-w-4xl mx-auto">
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900">System Settings</h1>
                        <p className="text-sm text-slate-500">Global configuration and secure keys.</p>
                    </div>
                    <button
                        onClick={handleSave}
                        disabled={updateSettings.isPending}
                        className="flex items-center gap-2 rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand/90 disabled:opacity-50"
                    >
                        <Save className="h-4 w-4" />
                        {updateSettings.isPending ? 'Saving...' : 'Save Changes'}
                    </button>
                </div>

                {message && (
                    <div className={`mb-6 rounded-lg border px-4 py-3 text-sm ${
                        message.type === 'success' ? 'border-green-200 bg-green-50 text-green-800' : 'border-red-200 bg-red-50 text-red-800'
                    }`}>
                        {message.text}
                    </div>
                )}

                <div className="space-y-6">
                    {/* Maintenance Mode */}
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <div className="flex items-center gap-2 mb-4">
                            <div className="p-2 bg-amber-50 rounded-lg">
                                <Bell className="h-5 w-5 text-amber-600" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">Maintenance Mode</h2>
                                <p className="text-sm text-slate-500">Show a maintenance screen on the Field Staff app.</p>
                            </div>
                        </div>

                        <div className="flex items-center justify-between gap-4 rounded-xl border border-slate-100 bg-slate-50 p-4">
                            <div>
                                <p className="text-sm font-semibold text-slate-900">Enable maintenance screen</p>
                                <p className="mt-1 text-xs text-slate-500">
                                    When enabled, field staff will see a maintenance message instead of the dashboard.
                                </p>
                            </div>
                            <label className="inline-flex items-center gap-3">
                                <span className="text-sm font-semibold text-slate-600">
                                    {String(formState[MAINTENANCE_KEY] ?? '0') === '1' ? 'ON' : 'OFF'}
                                </span>
                                <input
                                    type="checkbox"
                                    checked={String(formState[MAINTENANCE_KEY] ?? '0') === '1'}
                                    onChange={(e) => setFormState((prev) => ({ ...prev, [MAINTENANCE_KEY]: e.target.checked ? '1' : '0' }))}
                                    className="h-5 w-5 accent-amber-600"
                                />
                            </label>
                        </div>
                    </div>

                    {/* Data Integrity QA */}
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <div className="flex items-center gap-2 mb-4">
                            <div className="p-2 bg-amber-50 rounded-lg">
                                <RefreshCw className="h-5 w-5 text-amber-600" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">QA: Remaining Quantity Fix</h2>
                                <p className="text-sm text-slate-500">Run a full integrity sweep to correct remaining quantities.</p>
                            </div>
                        </div>

                        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 p-4">
                            <div>
                                <p className="text-sm font-semibold text-slate-900">Force QA recalculation now</p>
                                <p className="mt-1 text-xs text-slate-500">
                                    This will scan all supply plans and fix any mismatches between planned, delivered, and remaining quantities.
                                </p>
                            </div>
                            <button
                                onClick={() => runQaFix.mutate()}
                                disabled={runQaFix.isPending}
                                className="flex items-center gap-2 rounded-lg bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-amber-700 disabled:opacity-50"
                            >
                                <RefreshCw className={`h-4 w-4 ${runQaFix.isPending ? 'animate-spin' : ''}`} />
                                {runQaFix.isPending ? 'Running QA...' : 'Run QA Now'}
                            </button>
                        </div>
                    </div>

                    {/* Delivery Quantity Rules */}
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <div className="flex items-center gap-2 mb-4">
                            <div className="p-2 bg-emerald-50 rounded-lg">
                                <Lock className="h-5 w-5 text-emerald-600" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">Delivery Quantity Rules</h2>
                                <p className="text-sm text-slate-500">Control how the mobile app handles over-expected quantities.</p>
                            </div>
                        </div>

                        <div className="flex items-center justify-between gap-4 rounded-xl border border-slate-100 bg-slate-50 p-4">
                            <div>
                                <p className="text-sm font-semibold text-slate-900">Accept quantities above expected (flag for review)</p>
                                <p className="mt-1 text-xs text-slate-500">
                                    When enabled, the system will accept deliveries above the remaining/expected quantity and mark them as <span className="font-semibold">Pending review</span> for the Coordinator.
                                </p>
                            </div>
                            <label className="inline-flex items-center gap-3">
                                <span className="text-sm font-semibold text-slate-600">
                                    {String(formState[OVERAGE_KEY] ?? '0') === '1' ? 'ON' : 'OFF'}
                                </span>
                                <input
                                    type="checkbox"
                                    checked={String(formState[OVERAGE_KEY] ?? '0') === '1'}
                                    onChange={(e) => setFormState((prev) => ({ ...prev, [OVERAGE_KEY]: e.target.checked ? '1' : '0' }))}
                                    className="h-5 w-5 accent-emerald-600"
                                />
                            </label>
                        </div>
                    </div>

                    {/* SMTP Settings */}
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <div className="flex items-center gap-2 mb-4">
                            <div className="p-2 bg-blue-50 rounded-lg">
                                <Mail className="h-5 w-5 text-blue-600" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">Email Configuration (SMTP2GO)</h2>
                                <p className="text-sm text-slate-500">Manage email delivery settings.</p>
                            </div>
                        </div>

                        <div className="grid gap-6 md:grid-cols-2">
                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700">SMTP2GO Email API Key</label>
                                <div className="relative mt-1">
                                    <input
                                        type={showSecrets['smtp_api_key'] ? 'text' : 'password'}
                                        value={formState['smtp_api_key'] || ''}
                                        onChange={(e) => setFormState(prev => ({ ...prev, smtp_api_key: e.target.value }))}
                                        className="block w-full rounded-lg border border-slate-200 pl-3 pr-10 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                        placeholder="Enter SMTP2GO Email API Key"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => toggleShow('smtp_api_key')}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showSecrets['smtp_api_key'] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                    </button>
                                </div>
                                <p className="mt-1 text-xs text-slate-500">
                                    {settingsData?.['smtp_api_key']?.is_set ? '✅ Currently set' : '⚠️ Not configured'}
                                </p>
                                <p className="mt-1 text-xs text-slate-500">
                                    If SMTP relay fields below are set, the system will use SMTP relay; otherwise it falls back to the Email API key.
                                </p>
                            </div>

                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700">Sender Email Address</label>
                                <input
                                    type="email"
                                    value={formState['smtp_sender_email'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, smtp_sender_email: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                                    placeholder="noreply@yourdomain.com"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700">SMTP Host</label>
                                <input
                                    type="text"
                                    value={formState['smtp_host'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, smtp_host: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                    placeholder="mail.smtp2go.com"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700">SMTP Port</label>
                                <input
                                    type="number"
                                    value={formState['smtp_port'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, smtp_port: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                    placeholder="587"
                                />
                            </div>

                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700">SMTP Username</label>
                                <input
                                    type="text"
                                    value={formState['smtp_username'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, smtp_username: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                    placeholder="Username"
                                />
                            </div>

                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700">SMTP Password</label>
                                <div className="relative mt-1">
                                    <input
                                        type={showSecrets['smtp_password'] ? 'text' : 'password'}
                                        value={formState['smtp_password'] || ''}
                                        onChange={(e) => setFormState(prev => ({ ...prev, smtp_password: e.target.value }))}
                                        className="block w-full rounded-lg border border-slate-200 pl-3 pr-10 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                        placeholder="Password"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => toggleShow('smtp_password')}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showSecrets['smtp_password'] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                    </button>
                                </div>
                                <p className="mt-1 text-xs text-slate-500">
                                    {settingsData?.['smtp_password']?.is_set ? '✅ Currently set' : '⚠️ Not configured'}
                                </p>
                            </div>

                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700">SMTP Encryption</label>
                                <select
                                    value={formState['smtp_encryption'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, smtp_encryption: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                                >
                                    <option value="">tls (recommended)</option>
                                    <option value="tls">tls</option>
                                    <option value="ssl">ssl</option>
                                    <option value="none">none</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    {/* Push Notification Settings */}
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <div className="flex items-center gap-2 mb-4">
                            <div className="p-2 bg-purple-50 rounded-lg">
                                <Bell className="h-5 w-5 text-purple-600" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">Push Notifications (VAPID)</h2>
                                <p className="text-sm text-slate-500">Configure web push keys.</p>
                            </div>
                        </div>

                        <div className="grid gap-6">
                            <div>
                                <label className="block text-sm font-medium text-slate-700">VAPID Public Key</label>
                                <input
                                    type="text"
                                    value={formState['vapid_public_key'] || ''}
                                    onChange={(e) => setFormState(prev => ({ ...prev, vapid_public_key: e.target.value }))}
                                    className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                    placeholder="Public Key"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700">VAPID Private Key</label>
                                <div className="relative mt-1">
                                    <input
                                        type={showSecrets['vapid_private_key'] ? 'text' : 'password'}
                                        value={formState['vapid_private_key'] || ''}
                                        onChange={(e) => setFormState(prev => ({ ...prev, vapid_private_key: e.target.value }))}
                                        className="block w-full rounded-lg border border-slate-200 pl-3 pr-10 py-2 text-sm focus:border-brand focus:outline-none font-mono"
                                        placeholder="Private Key"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => toggleShow('vapid_private_key')}
                                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                                    >
                                        {showSecrets['vapid_private_key'] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                    </button>
                                </div>
                                <p className="mt-1 text-xs text-slate-500">
                                    {settingsData?.['vapid_private_key']?.is_set ? '✅ Currently set' : '⚠️ Not configured'}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </LayoutShell>
    );
}
