import { useState, useEffect } from 'react';
import { Save, CheckSquare, Settings, Camera, Loader2 } from 'lucide-react';
import { settingsApi, WalkthroughSettings, PhotoRequirement } from '../lib/settingsApi';
import { PageHeader } from '../components/ui/LinearPrimitives';
import { useToast } from '../context/ToastContext';

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="max-w-2xl mx-auto space-y-6">
                <PageHeader title="Walkthrough Settings" subtitle="Loading..." />
                <div className="card p-8 flex justify-center">
                    <Loader2 className="animate-spin text-tertiary" size={24} />
                </div>
            </div>
        );
    }

    // Toggle switch component
    const Toggle = ({ checked, onChange, label }: { checked: boolean; onChange: () => void; label: string }) => (
        <label className="flex items-center justify-between p-3 rounded-md hover:bg-tertiary transition-colors duration-fast cursor-pointer">
            <span className="text-sm text-primary">{label}</span>
            <button
                type="button"
                role="switch"
                aria-checked={checked}
                onClick={onChange}
                className={`
                    relative w-10 h-6 rounded-full transition-colors duration-fast
                    ${checked ? 'bg-accent' : 'bg-tertiary'}
                `}
            >
                <span
                    className={`
                        absolute top-1 left-1 w-4 h-4 bg-white rounded-full
                        transition-transform duration-fast
                        ${checked ? 'translate-x-4' : ''}
                    `}
                />
            </button>
        </label>
    );

    return (
        <div className="max-w-2xl mx-auto space-y-6 pb-20 animate-in">
            <PageHeader
                title="Walkthrough Settings"
                subtitle="Configure daily checklist requirements"
            />

            <form onSubmit={handleUpdate} className="space-y-6">
                {/* Enabled Sections */}
                <div className="card">
                    <div className="p-4 border-b border-subtle flex items-center gap-2">
                        <CheckSquare size={16} className="text-accent" />
                        <h3 className="text-sm font-medium text-primary">Enabled Modules</h3>
                    </div>
                    <div className="p-2">
                        <Toggle
                            checked={settings.enableReservoirs}
                            onChange={() => setSettings({ ...settings, enableReservoirs: !settings.enableReservoirs })}
                            label="Reservoir Checks"
                        />
                        <Toggle
                            checked={settings.enableIrrigation}
                            onChange={() => setSettings({ ...settings, enableIrrigation: !settings.enableIrrigation })}
                            label="Irrigation Checks"
                        />
                        <Toggle
                            checked={settings.enablePlantHealth}
                            onChange={() => setSettings({ ...settings, enablePlantHealth: !settings.enablePlantHealth })}
                            label="Plant Health Checks"
                        />
                    </div>
                </div>

                {/* Photo Requirements */}
                <div className="card">
                    <div className="p-4 border-b border-subtle flex items-center gap-2">
                        <Camera size={16} className="text-accent" />
                        <h3 className="text-sm font-medium text-primary">Photo Requirements</h3>
                    </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"
                            >
                                {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"
                            >
                                {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"
                            >
                                {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 h-12"
                >
                    {isSaving ? (
                        <>
                            <Loader2 size={16} className="animate-spin" />
                            Saving...
                        </>
                    ) : (
                        <>
                            <Save size={16} />
                            Save Configuration
                        </>
                    )}
                </button>
            </form>
        </div>
    );
}
