import { useState, useEffect, useCallback } from 'react';
import { Tabs, TabList, Tab } from '@/components/application/tabs/tabs';
import { Button } from '@/components/base/buttons/button';
import { PriorityConfigPanel } from '@/components/rules/priority-config-panel';
import { CampaignWeightsPanel } from '@/components/rules/campaign-weights-panel';
import { SourceWeightsPanel } from '@/components/rules/source-weights-panel';
import { WorklistPreview } from '@/components/rules/worklist-preview';
import { RulesAiAssistant } from '@/components/rules/rules-ai-assistant';
import { DEFAULT_PRIORITY_CONFIG } from '@/lib/scoring';
import type { PriorityConfig } from '@/lib/scoring';
const API_BASE = import.meta.env.VITE_SIDECAR_URL ?? 'http://localhost:4100';
const getToken = () => localStorage.getItem('helix_access_token');

export const RulesSettingsPage = () => {
    const token = getToken();
    const [config, setConfig] = useState<PriorityConfig>(DEFAULT_PRIORITY_CONFIG);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [dirty, setDirty] = useState(false);


    useEffect(() => {
        const load = async () => {
            try {
                const res = await fetch(`${API_BASE}/api/rules/priority-config`, {
                    headers: token ? { Authorization: `Bearer ${token}` } : {},
                });
                if (res.ok) {
                    const data = await res.json();
                    setConfig(data);
                }
            } catch {
                // Fallback to defaults
            } finally {
                setLoading(false);
            }
        };
        load();
    }, [token]);

    const saveConfig = useCallback(async (newConfig: PriorityConfig) => {
        try {
            setSaving(true);
            await fetch(`${API_BASE}/api/rules/priority-config`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token ? { Authorization: `Bearer ${token}` } : {}),
                },
                body: JSON.stringify(newConfig),
            });
            setDirty(false);
        } catch {
            // Silent fail
        } finally {
            setSaving(false);
        }
    }, [token]);

    const handleConfigChange = (newConfig: PriorityConfig) => {
        setConfig(newConfig);
        setDirty(true);
    };

    const applyTemplate = async () => {
        try {
            await saveConfig(DEFAULT_PRIORITY_CONFIG);
            setConfig(DEFAULT_PRIORITY_CONFIG);
            setDirty(false);
        } catch {
            // Silent fail
        }
    };

    if (loading) {
        return (
            <div className="flex h-full items-center justify-center">
                <div className="text-sm text-tertiary">Loading rules configuration...</div>
            </div>
        );
    }

    return (
        <div className="flex h-full flex-col overflow-hidden">
            {/* Header */}
            <div className="shrink-0 flex items-center justify-between border-b border-secondary px-6 py-4">
                <div>
                    <h1 className="text-lg font-bold text-primary">Rules Engine</h1>
                    <p className="text-sm text-tertiary">Configure how leads are prioritized and routed in the worklist</p>
                </div>
                <div className="flex items-center gap-3">
                    {dirty && <span className="text-xs text-warning-primary">{saving ? 'Saving...' : 'Unsaved changes'}</span>}
                    <Button size="sm" color="secondary" onClick={applyTemplate}>
                        Reset to Defaults
                    </Button>
                    {dirty && (
                        <Button size="sm" color="primary" isLoading={saving} onClick={() => saveConfig(config)}>
                            Apply Changes
                        </Button>
                    )}
                </div>
            </div>

            {/* Tabs + Content — fills remaining height */}
            <div className="flex flex-1 flex-col min-h-0">
                <Tabs aria-label="Rules configuration" className="flex flex-1 flex-col min-h-0">
                    <div className="shrink-0 border-b border-secondary px-6 pt-2">
                        <TabList items={[{ id: 'priority', label: 'Priority Rules' }, { id: 'automations', label: 'Automations' }]} type="underline" size="sm">
                            {(item) => <Tab key={item.id} id={item.id} label={item.label} />}
                        </TabList>
                    </div>

                    <Tabs.Panel id="priority" className="flex flex-1 min-h-0">
                        <div className="flex flex-1 min-h-0">
                            {/* Left — config panels, scrollable */}
                            <div className="flex-1 overflow-y-auto p-6 space-y-8">
                                <PriorityConfigPanel config={config} onChange={handleConfigChange} />
                                <CampaignWeightsPanel config={config} onChange={handleConfigChange} />
                                <SourceWeightsPanel config={config} onChange={handleConfigChange} />
                            </div>

                            {/* Right — preview + collapsible AI */}
                            <div className="w-[400px] shrink-0 border-l border-secondary flex flex-col min-h-0 bg-secondary">
                                {/* Preview — takes available space */}
                                <div className="flex-1 overflow-y-auto p-4 min-h-0">
                                    <WorklistPreview config={config} />
                                </div>

                                {/* AI Assistant — collapsible at bottom */}
                                <RulesAiAssistant config={config} />
                            </div>
                        </div>
                    </Tabs.Panel>

                    <Tabs.Panel id="automations" className="flex flex-1 min-h-0">
                        <div className="flex-1 overflow-y-auto p-6 space-y-4">
                            <div className="flex items-center justify-between mb-2">
                                <div>
                                    <h3 className="text-sm font-semibold text-primary">Automation Rules</h3>
                                    <p className="text-xs text-tertiary">Rules that trigger actions when conditions are met — assign leads, escalate breaches, update status.</p>
                                </div>
                            </div>

                            {[
                                { name: 'SLA Breach → Supervisor Alert', description: 'Alert supervisor when a missed call callback exceeds 12-hour SLA', trigger: 'Every 5 minutes', condition: 'SLA > 100% AND status = PENDING_CALLBACK', action: 'Notify supervisor via bell + toast', category: 'escalation', enabled: true },
                                { name: 'Cold Lead after 3 Attempts', description: 'Mark lead as COLD when 3 contact attempts fail', trigger: 'On call ended', condition: 'Contact attempts ≥ 3 AND disposition ≠ APPOINTMENT_BOOKED', action: 'Update lead status → COLD', category: 'lifecycle', enabled: true },
                                { name: 'Round-robin Lead Assignment', description: 'Distribute new campaign leads evenly across available agents', trigger: 'On lead created', condition: 'assignedAgent is empty AND agent status = READY', action: 'Assign to least-loaded ready agent', category: 'assignment', enabled: false },
                                { name: 'Follow-up Reminder at 80% SLA', description: 'Push notification when a follow-up approaches its SLA deadline', trigger: 'Every 5 minutes', condition: 'SLA elapsed ≥ 80% AND status = PENDING', action: 'Notify assigned agent via bell', category: 'escalation', enabled: true },
                                { name: 'Spam Lead Auto-close', description: 'Automatically close leads with spam score above 80', trigger: 'On lead updated', condition: 'Spam score > 80', action: 'Update lead status → SPAM_CLOSED', category: 'lifecycle', enabled: false },
                                { name: 'VIP Patient Escalation', description: 'Escalate to supervisor when a returning patient calls and waits over 5 minutes', trigger: 'Every 1 minute', condition: 'Patient type = RETURNING AND wait time > 5 min', action: 'Notify supervisor + assign to next available agent', category: 'escalation', enabled: false },
                            ].map((rule, i) => {
                                const categoryColors: Record<string, string> = {
                                    escalation: 'bg-error-secondary text-error-primary',
                                    lifecycle: 'bg-warning-secondary text-warning-primary',
                                    assignment: 'bg-brand-secondary text-brand-secondary',
                                };
                                return (
                                    <div key={i} className="rounded-xl border border-secondary bg-primary p-4">
                                        <div className="flex items-start justify-between">
                                            <div className="flex-1">
                                                <div className="flex items-center gap-2 mb-1">
                                                    <span className="text-sm font-semibold text-primary">{rule.name}</span>
                                                    <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${categoryColors[rule.category] ?? 'bg-secondary text-tertiary'}`}>
                                                        {rule.category}
                                                    </span>
                                                </div>
                                                <p className="text-xs text-tertiary mb-3">{rule.description}</p>
                                                <div className="grid grid-cols-3 gap-3 text-xs">
                                                    <div>
                                                        <span className="font-semibold text-quaternary uppercase tracking-wider text-[10px]">Trigger</span>
                                                        <p className="text-secondary mt-0.5">{rule.trigger}</p>
                                                    </div>
                                                    <div>
                                                        <span className="font-semibold text-quaternary uppercase tracking-wider text-[10px]">Condition</span>
                                                        <p className="text-secondary mt-0.5">{rule.condition}</p>
                                                    </div>
                                                    <div>
                                                        <span className="font-semibold text-quaternary uppercase tracking-wider text-[10px]">Action</span>
                                                        <p className="text-secondary mt-0.5">{rule.action}</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="shrink-0 ml-4 flex flex-col items-center gap-1">
                                                <div className={`size-3 rounded-full ${rule.enabled ? 'bg-success-solid' : 'bg-quaternary'}`} />
                                                <span className="text-[10px] text-tertiary">{rule.enabled ? 'On' : 'Off'}</span>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}

                            <p className="text-xs text-tertiary text-center pt-2">Rule editing and creation will be available in a future update.</p>
                        </div>
                    </Tabs.Panel>
                </Tabs>
            </div>
        </div>
    );
};
