import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Save, CheckSquare, Camera, Loader2, ArrowLeft, Droplets, Sprout, Bug } from 'lucide-react';
import { settingsApi, WalkthroughSettings, PhotoRequirement } from '../lib/settingsApi';
import { useToast } from '../context/ToastContext';
import { cn } from '../lib/utils';

const PHOTO_OPTIONS: { label: string; value: PhotoRequirement }[] = [
    { label: 'Always Required', value: 'REQUIRED' },
    { label: 'Optional', value: 'OPTIONAL' },
    { label: 'Weekly Only', value: 'WEEKLY' },
    { label: 'On Demand', value: 'ON_DEMAND' },
];

export default function WalkthroughSettingsPage() {
    const { addToast } = useToast();
    const [settings, setSettings] = useState<WalkthroughSettings | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isSaving, setIsSaving] = useState(false);

    useEffect(() => {
        loadSettings();
    }, []);

    const loadSettings = async () => {
        setIsLoading(true);
        try {
            const data = await settingsApi.getWalkthrough();
            setSettings(data);
        } catch (e) {
            console.error(e);
            addToast('Failed to load settings', 'error');
        } finally {
            setIsLoading(false);
        }
    };

    const handleUpdate = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!settings) return;

        setIsSaving(true);
        try {
            await settingsApi.updateWalkthrough(settings);
            addToast('Settings saved!', 'success');
        } catch (e) {
            console.error(e);
            addToast('Failed to save settings', 'error');
        } finally {
            setIsSaving(false);
        }
    };

    if (isLoading || !settings) {
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center">
                <div className="text-center">
                    <Loader2 className="animate-spin text-accent mx-auto mb-4" size={32} />
                    <p className="text-tertiary text-sm">Loading settings...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-primary pb-20">
            {/* Header */}
            <div className="sticky top-0 z-20 bg-elevated border-b border-subtle">
                <div className="max-w-2xl mx-auto px-4 py-3">
                    <div className="flex items-center gap-3">
                        <Link to="/settings" className="p-2 -ml-2 rounded-lg hover:bg-tertiary text-tertiary">
                            <ArrowLeft size={20} />
                        </Link>
                        <div>
                            <h1 className="text-base font-semibold text-primary">Walkthrough Settings</h1>
                            <p className="text-xs text-tertiary">Configure daily checklist</p>
                        </div>
                    </div>
                </div>
            </div>

            <div className="max-w-2xl mx-auto px-4 py-6">
                <form onSubmit={handleUpdate} className="space-y-6">
                    {/* Enabled Modules */}
                    <div className="card">
                        <div className="p-4 border-b border-subtle flex items-center gap-3">
                            <CheckSquare size={16} className="text-accent" />
                            <span className="text-sm font-medium text-primary">Enabled Modules</span>
                        </div>
                        <div className="divide-y divide-subtle">
                            <Toggle
                                checked={settings.enableReservoirs}
                                onChange={() => setSettings({ ...settings, enableReservoirs: !settings.enableReservoirs })}
                                label="Reservoir Checks"
                                description="Tank levels and nutrients"
                                icon={Droplets}
                            />
                            <Toggle
                                checked={settings.enableIrrigation}
                                onChange={() => setSettings({ ...settings, enableIrrigation: !settings.enableIrrigation })}
                                label="Irrigation Checks"
                                description="Dripper counts and flow"
                                icon={Sprout}
                            />
                            <Toggle
                                checked={settings.enablePlantHealth}
                                onChange={() => setSettings({ ...settings, enablePlantHealth: !settings.enablePlantHealth })}
                                label="Plant Health Checks"
                                description="Visual inspections"
                                icon={Bug}
                            />
                        </div>
                    </div>

                    {/* Photo Requirements */}
                    <div className="card">
                        <div className="p-4 border-b border-subtle flex items-center gap-3">
                            <Camera size={16} className="text-accent" />
                            <span className="text-sm font-medium text-primary">Photo Requirements</span>
                        </div>
                        <div className="p-4 space-y-4">
                            <div>
                                <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                    Reservoirs
                                </label>
                                <select
                                    value={settings.reservoirPhotos}
                                    onChange={e => setSettings({ ...settings, reservoirPhotos: e.target.value as PhotoRequirement })}
                                    className="input w-full py-3"
                                >
                                    {PHOTO_OPTIONS.map(opt => (
                                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                    Irrigation
                                </label>
                                <select
                                    value={settings.irrigationPhotos}
                                    onChange={e => setSettings({ ...settings, irrigationPhotos: e.target.value as PhotoRequirement })}
                                    className="input w-full py-3"
                                >
                                    {PHOTO_OPTIONS.map(opt => (
                                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                    Plant Health
                                </label>
                                <select
                                    value={settings.plantHealthPhotos}
                                    onChange={e => setSettings({ ...settings, plantHealthPhotos: e.target.value as PhotoRequirement })}
                                    className="input w-full py-3"
                                >
                                    {PHOTO_OPTIONS.map(opt => (
                                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                                    ))}
                                </select>
                            </div>
                        </div>
                    </div>

                    <button
                        type="submit"
                        disabled={isSaving}
                        className="btn btn-primary w-full py-4 text-base"
                    >
                        {isSaving ? (
                            <><Loader2 size={18} className="animate-spin" /> Saving...</>
                        ) : (
                            <><Save size={18} /> Save Settings</>
                        )}
                    </button>
                </form>
            </div>
        </div>
    );
}

// Toggle component
function Toggle({ checked, onChange, label, description, icon: Icon }: {
    checked: boolean;
    onChange: () => void;
    label: string;
    description?: string;
    icon?: typeof Droplets;
}) {
    return (
        <label className="flex items-center justify-between p-4 hover:bg-tertiary transition-colors cursor-pointer active:bg-secondary">
            <div className="flex items-center gap-3">
                {Icon && (
                    <div className={cn(
                        "w-10 h-10 rounded-lg flex items-center justify-center",
                        checked ? "bg-accent-muted text-accent" : "bg-tertiary text-tertiary"
                    )}>
                        <Icon size={18} />
                    </div>
                )}
                <div>
                    <span className="text-sm font-medium text-primary">{label}</span>
                    {description && <p className="text-xs text-tertiary">{description}</p>}
                </div>
            </div>
            <button
                type="button"
                role="switch"
                aria-checked={checked}
                onClick={onChange}
                className={cn(
                    "relative w-12 h-7 rounded-full transition-colors",
                    checked ? 'bg-accent' : 'bg-tertiary'
                )}
            >
                <span
                    className={cn(
                        "absolute top-1 w-5 h-5 bg-white rounded-full shadow transition-transform",
                        checked ? 'translate-x-6' : 'translate-x-1'
                    )}
                />
            </button>
        </label>
    );
}
