import { useState, useEffect, useRef } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { settingsApi, WalkthroughSettings } from '../lib/settingsApi';
import { walkthroughApi, ReservoirCheckData, IrrigationCheckData, PlantHealthCheckData, Walkthrough } from '../lib/walkthroughApi';
import {
    Check, Loader2, Droplets, Sprout, Bug, ArrowLeft,
    Camera, X, Minus, Plus, ChevronDown, ChevronUp, Upload, CheckCircle2, Clock, Mic, MicOff
} from 'lucide-react';
import { useToast } from '../context/ToastContext';
import { cn } from '../lib/utils';

// Tank/Zone configs - simplified for clarity
const TANKS = [
    { name: 'Veg Tank 1', type: 'VEG' as const },
    { name: 'Veg Tank 2', type: 'VEG' as const },
    { name: 'Flower Tank 1', type: 'FLOWER' as const },
    { name: 'Flower Tank 2', type: 'FLOWER' as const },
];

const ZONES = [
    { name: 'Veg Upstairs', drippers: 48 },
    { name: 'Veg Downstairs', drippers: 48 },
    { name: 'Flower Upstairs', drippers: 64 },
    { name: 'Flower Downstairs', drippers: 64 },
];

const HEALTH_ZONES = ['Veg Upstairs', 'Veg Downstairs', 'Flower Upstairs', 'Flower Downstairs'];

export default function DailyWalkthroughPage() {
    const navigate = useNavigate();
    const { addToast } = useToast();
    const [walkthroughId, setWalkthroughId] = useState<string | null>(null);
    const [isStarting, setIsStarting] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [settings, setSettings] = useState<WalkthroughSettings | null>(null);
    const [todaysWalkthrough, setTodaysWalkthrough] = useState<Walkthrough | null>(null);

    // All check states
    const [reservoirChecks, setReservoirChecks] = useState<Record<string, ReservoirCheckData>>({});
    const [irrigationChecks, setIrrigationChecks] = useState<Record<string, IrrigationCheckData>>({});
    const [plantHealthChecks, setPlantHealthChecks] = useState<Record<string, PlantHealthCheckData>>({});

    // Section expansion
    const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
        reservoirs: true,
        irrigation: false,
        plantHealth: false,
    });

    useEffect(() => {
        const loadData = async () => {
            setIsLoading(true);
            try {
                const [settingsData, todayData] = await Promise.all([
                    settingsApi.getWalkthrough().catch(() => null),
                    walkthroughApi.getToday().catch(() => null)
                ]);
                setSettings(settingsData);
                setTodaysWalkthrough(todayData);
            } catch (error) {
                console.error('Failed to load walkthrough data:', error);
            } finally {
                setIsLoading(false);
            }
        };
        loadData();
    }, []);

    const toggleSection = (section: string) => {
        setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
    };

    const handleStart = async () => {
        setIsStarting(true);
        try {
            const walkthrough = await walkthroughApi.create();
            setWalkthroughId(walkthrough.id);
        } catch (err: any) {
            addToast('Failed to start walkthrough', 'error');
        } finally {
            setIsStarting(false);
        }
    };

    const handleSubmit = async () => {
        if (!walkthroughId) return;
        setIsSubmitting(true);
        try {
            for (const check of Object.values(reservoirChecks)) {
                await walkthroughApi.addReservoirCheck(walkthroughId, check);
            }
            for (const check of Object.values(irrigationChecks)) {
                await walkthroughApi.addIrrigationCheck(walkthroughId, check);
            }
            for (const check of Object.values(plantHealthChecks)) {
                await walkthroughApi.addPlantHealthCheck(walkthroughId, check);
            }
            await walkthroughApi.complete(walkthroughId);
            addToast('Walkthrough completed!', 'success');
            navigate('/');
        } catch (err: any) {
            addToast('Failed to submit walkthrough', 'error');
        } finally {
            setIsSubmitting(false);
        }
    };

    const totalChecks = Object.keys(reservoirChecks).length + Object.keys(irrigationChecks).length + Object.keys(plantHealthChecks).length;
    const requiredChecks = TANKS.length + ZONES.length + HEALTH_ZONES.length;
    const isComplete = totalChecks === requiredChecks;
    const progressPercent = Math.round((totalChecks / requiredChecks) * 100);

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

    // Already completed today
    if (todaysWalkthrough?.status === 'COMPLETED' && !walkthroughId) {
        const completedTime = new Date(todaysWalkthrough.endTime || todaysWalkthrough.startTime);
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center p-6">
                <div className="w-full max-w-sm text-center">
                    <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-success/20 flex items-center justify-center">
                        <CheckCircle2 size={40} className="text-success" />
                    </div>
                    <h1 className="text-xl font-semibold text-primary mb-2">Walkthrough Complete</h1>
                    <p className="text-sm text-tertiary mb-4">
                        {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
                    </p>
                    <div className="card p-4 mb-6">
                        <div className="flex items-center justify-center gap-2 text-success">
                            <Clock size={16} />
                            <span className="font-medium">
                                {completedTime.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                            </span>
                        </div>
                        {todaysWalkthrough.user?.name && (
                            <p className="text-xs text-tertiary mt-1">by {todaysWalkthrough.user.name}</p>
                        )}
                    </div>
                    <Link to="/" className="btn btn-primary w-full py-4 text-base">
                        Back to Dashboard
                    </Link>
                    <button
                        onClick={() => setTodaysWalkthrough(null)}
                        className="block w-full mt-4 text-sm text-tertiary hover:text-secondary py-2"
                    >
                        Start new walkthrough anyway
                    </button>
                </div>
            </div>
        );
    }

    // In-progress walkthrough
    if (todaysWalkthrough?.status === 'IN_PROGRESS' && !walkthroughId) {
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center p-6">
                <div className="w-full max-w-sm text-center">
                    <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-warning/20 flex items-center justify-center">
                        <Clock size={40} className="text-warning" />
                    </div>
                    <h1 className="text-xl font-semibold text-primary mb-2">Walkthrough In Progress</h1>
                    <p className="text-sm text-tertiary mb-6">
                        Started {new Date(todaysWalkthrough.startTime).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                    </p>
                    <button
                        onClick={() => setWalkthroughId(todaysWalkthrough.id)}
                        className="btn btn-primary w-full py-4 text-base"
                    >
                        Continue
                    </button>
                    <Link to="/" className="block mt-4 text-sm text-tertiary hover:text-secondary py-2">
                        ← Back
                    </Link>
                </div>
            </div>
        );
    }

    // Pre-start view
    if (!walkthroughId) {
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center p-6">
                <div className="w-full max-w-md text-center">
                    <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-accent-muted flex items-center justify-center">
                        <Sprout size={36} className="text-accent" />
                    </div>
                    <h1 className="text-2xl font-semibold text-primary mb-2">Daily Walkthrough</h1>
                    <p className="text-sm text-tertiary mb-8">
                        {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
                    </p>

                    {/* Simple checklist preview */}
                    <div className="card p-4 mb-6 text-left space-y-3">
                        <div className="flex items-center gap-3 text-sm text-secondary">
                            <Droplets size={18} className="text-accent flex-shrink-0" />
                            <span>Reservoir Levels</span>
                            <span className="ml-auto text-tertiary">{TANKS.length}</span>
                        </div>
                        <div className="flex items-center gap-3 text-sm text-secondary">
                            <Sprout size={18} className="text-accent flex-shrink-0" />
                            <span>Irrigation Zones</span>
                            <span className="ml-auto text-tertiary">{ZONES.length}</span>
                        </div>
                        <div className="flex items-center gap-3 text-sm text-secondary">
                            <Bug size={18} className="text-accent flex-shrink-0" />
                            <span>Plant Health</span>
                            <span className="ml-auto text-tertiary">{HEALTH_ZONES.length}</span>
                        </div>
                    </div>

                    <button
                        onClick={handleStart}
                        disabled={isStarting}
                        className="btn btn-primary w-full py-4 text-base"
                    >
                        {isStarting ? <Loader2 size={20} className="animate-spin" /> : 'Start Walkthrough'}
                    </button>
                    <Link to="/" className="block mt-4 text-sm text-tertiary hover:text-secondary py-2">
                        ← Back to Dashboard
                    </Link>
                </div>
            </div>
        );
    }

    // Active walkthrough
    return (
        <div className="min-h-screen bg-primary pb-28">
            {/* Header - fixed with progress */}
            <div className="sticky top-0 z-20 bg-elevated border-b border-subtle">
                <div className="max-w-4xl mx-auto px-4 py-3">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <Link to="/" 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">Daily Walkthrough</h1>
                                <p className="text-xs text-tertiary">
                                    {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                                </p>
                            </div>
                        </div>

                        {/* Progress indicator */}
                        <div className="flex items-center gap-2">
                            <span className="text-lg font-bold text-accent">{totalChecks}</span>
                            <span className="text-sm text-tertiary">/ {requiredChecks}</span>
                        </div>
                    </div>

                    {/* Progress bar */}
                    <div className="mt-3 h-1.5 bg-tertiary rounded-full overflow-hidden">
                        <div
                            className="h-full bg-accent transition-all duration-300"
                            style={{ width: `${progressPercent}%` }}
                        />
                    </div>
                </div>
            </div>

            {/* Sections */}
            <div className="max-w-4xl mx-auto px-4 py-4 space-y-3">
                {/* Reservoirs */}
                {settings?.enableReservoirs !== false && (
                    <Section
                        title="Reservoir Levels"
                        icon={Droplets}
                        count={Object.keys(reservoirChecks).length}
                        total={TANKS.length}
                        expanded={expandedSections.reservoirs}
                        onToggle={() => toggleSection('reservoirs')}
                    >
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            {TANKS.map(tank => (
                                <ReservoirCard
                                    key={tank.name}
                                    tank={tank}
                                    data={reservoirChecks[tank.name]}
                                    onChange={(data) => setReservoirChecks(prev => ({ ...prev, [tank.name]: data }))}
                                />
                            ))}
                        </div>
                    </Section>
                )}

                {/* Irrigation */}
                {settings?.enableIrrigation !== false && (
                    <Section
                        title="Irrigation Zones"
                        icon={Sprout}
                        count={Object.keys(irrigationChecks).length}
                        total={ZONES.length}
                        expanded={expandedSections.irrigation}
                        onToggle={() => toggleSection('irrigation')}
                    >
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            {ZONES.map(zone => (
                                <IrrigationCard
                                    key={zone.name}
                                    zone={zone}
                                    data={irrigationChecks[zone.name]}
                                    onChange={(data) => setIrrigationChecks(prev => ({ ...prev, [zone.name]: data }))}
                                />
                            ))}
                        </div>
                    </Section>
                )}

                {/* Plant Health */}
                {settings?.enablePlantHealth !== false && (
                    <Section
                        title="Plant Health"
                        icon={Bug}
                        count={Object.keys(plantHealthChecks).length}
                        total={HEALTH_ZONES.length}
                        expanded={expandedSections.plantHealth}
                        onToggle={() => toggleSection('plantHealth')}
                    >
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            {HEALTH_ZONES.map(zone => (
                                <HealthCard
                                    key={zone}
                                    zoneName={zone}
                                    data={plantHealthChecks[zone]}
                                    onChange={(data) => setPlantHealthChecks(prev => ({ ...prev, [zone]: data }))}
                                />
                            ))}
                        </div>
                    </Section>
                )}
            </div>

            {/* Submit button - fixed bottom */}
            <div className="fixed bottom-0 left-0 right-0 p-4 bg-elevated border-t border-subtle">
                <div className="max-w-4xl mx-auto">
                    <button
                        onClick={handleSubmit}
                        disabled={!isComplete || isSubmitting}
                        className={cn(
                            "btn w-full py-4 text-base",
                            isComplete ? "btn-primary" : "bg-tertiary text-tertiary cursor-not-allowed"
                        )}
                    >
                        {isSubmitting ? (
                            <><Loader2 size={18} className="animate-spin" /> Submitting...</>
                        ) : isComplete ? (
                            <><Check size={18} /> Submit Walkthrough</>
                        ) : (
                            `${totalChecks} of ${requiredChecks} checks complete`
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}

// Section component
function Section({
    title, icon: Icon, count, total, expanded, onToggle, children
}: {
    title: string;
    icon: typeof Droplets;
    count: number;
    total: number;
    expanded: boolean;
    onToggle: () => void;
    children: React.ReactNode;
}) {
    const done = count === total;
    return (
        <div className="card overflow-hidden">
            <button
                onClick={onToggle}
                className="w-full flex items-center justify-between p-4 hover:bg-tertiary transition-colors active:bg-secondary"
            >
                <div className="flex items-center gap-3">
                    <div className={cn(
                        "w-10 h-10 rounded-lg flex items-center justify-center",
                        done ? "bg-success/20 text-success" : "bg-accent-muted text-accent"
                    )}>
                        {done ? <Check size={18} /> : <Icon size={18} />}
                    </div>
                    <div className="text-left">
                        <span className="text-sm font-medium text-primary">{title}</span>
                        <p className="text-xs text-tertiary">{count} / {total}</p>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {done && <span className="text-xs text-success font-medium">Done</span>}
                    {expanded ? <ChevronUp size={18} className="text-tertiary" /> : <ChevronDown size={18} className="text-tertiary" />}
                </div>
            </button>
            {expanded && <div className="p-4 pt-0 border-t border-subtle">{children}</div>}
        </div>
    );
}

// Photo capture - mobile optimized
function PhotoButton({ photoUrl, onCapture }: { photoUrl?: string | null; onCapture: (url: string | null) => void }) {
    const inputRef = useRef<HTMLInputElement>(null);

    const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) onCapture(URL.createObjectURL(file));
    };

    if (photoUrl) {
        return (
            <div className="relative">
                <img src={photoUrl} alt="Photo" className="w-full h-24 object-cover rounded-lg" />
                <button
                    onClick={() => onCapture(null)}
                    className="absolute top-1 right-1 w-6 h-6 bg-destructive text-white rounded-full flex items-center justify-center"
                >
                    <X size={12} />
                </button>
            </div>
        );
    }

    return (
        <>
            <input ref={inputRef} type="file" accept="image/*" capture="environment" onChange={handleFile} className="hidden" />
            <button
                type="button"
                onClick={() => inputRef.current?.click()}
                className="flex items-center justify-center gap-2 w-full py-3 bg-tertiary text-secondary rounded-lg text-sm font-medium active:bg-secondary"
            >
                <Camera size={16} />
                Add Photo
            </button>
        </>
    );
}

// Voice input for notes - uses Web Speech API
function VoiceInput({ value, onChange, placeholder }: { value: string; onChange: (v: string) => void; placeholder?: string }) {
    const [isListening, setIsListening] = useState(false);
    const recognitionRef = useRef<any>(null);

    const startListening = () => {
        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            alert('Voice input not supported in this browser');
            return;
        }

        const SpeechRecognition = (window as any).webkitSpeechRecognition || (window as any).SpeechRecognition;
        recognitionRef.current = new SpeechRecognition();
        recognitionRef.current.continuous = false;
        recognitionRef.current.interimResults = false;
        recognitionRef.current.lang = 'en-US';

        recognitionRef.current.onresult = (event: any) => {
            const transcript = event.results[0][0].transcript;
            onChange(value ? `${value} ${transcript}` : transcript);
            setIsListening(false);
        };

        recognitionRef.current.onerror = () => setIsListening(false);
        recognitionRef.current.onend = () => setIsListening(false);

        recognitionRef.current.start();
        setIsListening(true);
    };

    const stopListening = () => {
        if (recognitionRef.current) {
            recognitionRef.current.stop();
        }
        setIsListening(false);
    };

    return (
        <div className="flex gap-2">
            <input
                type="text"
                value={value}
                onChange={(e) => onChange(e.target.value)}
                placeholder={placeholder}
                className="input flex-1 py-3"
            />
            <button
                type="button"
                onClick={isListening ? stopListening : startListening}
                className={cn(
                    "w-12 h-12 rounded-lg flex items-center justify-center transition-colors",
                    isListening ? "bg-destructive text-white animate-pulse" : "bg-tertiary text-secondary active:bg-secondary"
                )}
            >
                {isListening ? <MicOff size={20} /> : <Mic size={20} />}
            </button>
        </div>
    );
}

// Reservoir card - large touch targets
function ReservoirCard({ tank, data, onChange }: {
    tank: { name: string; type: 'VEG' | 'FLOWER' };
    data?: ReservoirCheckData;
    onChange: (data: ReservoirCheckData) => void;
}) {
    const [level, setLevel] = useState(data?.levelPercent ?? 100);
    const [photo, setPhoto] = useState<string | null>(data?.photoUrl || null);
    const [notes, setNotes] = useState(data?.notes || '');

    const getStatus = (l: number) => l >= 70 ? 'OK' : l >= 30 ? 'LOW' : 'CRITICAL';
    const statusColor = getStatus(level) === 'OK' ? 'success' : getStatus(level) === 'LOW' ? 'warning' : 'destructive';

    const handleSave = () => {
        onChange({
            tankName: tank.name,
            tankType: tank.type,
            levelPercent: level,
            status: getStatus(level),
            photoUrl: photo || undefined,
            notes: notes || undefined,
        });
    };

    // If already saved, show compact view
    if (data) {
        return (
            <div className="flex items-center justify-between p-4 bg-tertiary rounded-lg">
                <div className="flex items-center gap-3">
                    <div className={cn("w-3 h-10 rounded-full", `bg-${statusColor}`)} />
                    <div>
                        <span className="text-sm font-medium text-primary">{tank.name}</span>
                        <p className="text-xs text-tertiary">{data.levelPercent}%</p>
                    </div>
                </div>
                <button
                    onClick={() => onChange(undefined as any)}
                    className="text-xs text-accent font-medium py-2 px-3"
                >
                    Edit
                </button>
            </div>
        );
    }

    return (
        <div className="p-4 bg-tertiary rounded-lg space-y-4">
            {/* Header */}
            <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-primary">{tank.name}</span>
                <span className={cn(
                    "text-xs px-2 py-0.5 rounded font-medium",
                    tank.type === 'VEG' ? 'bg-success/20 text-success' : 'bg-accent/20 text-accent'
                )}>
                    {tank.type}
                </span>
            </div>

            {/* Level - large slider for touch */}
            <div className="space-y-2">
                <div className="flex items-center justify-between">
                    <span className="text-xs text-tertiary">Level</span>
                    <span className={cn("text-xl font-bold", `text-${statusColor}`)}>{level}%</span>
                </div>
                <input
                    type="range"
                    min="0"
                    max="100"
                    step="5"
                    value={level}
                    onChange={(e) => setLevel(parseInt(e.target.value))}
                    className="w-full h-3 bg-secondary rounded-full appearance-none cursor-pointer accent-accent"
                />
                <div className="flex justify-between text-[10px] text-tertiary">
                    <span>Empty</span>
                    <span>Full</span>
                </div>
            </div>

            {/* Notes with voice */}
            <VoiceInput value={notes} onChange={setNotes} placeholder="Notes (optional)" />

            {/* Photo */}
            <PhotoButton photoUrl={photo} onCapture={setPhoto} />

            {/* Save - large button */}
            <button onClick={handleSave} className="btn btn-primary w-full py-4">
                Save
            </button>
        </div>
    );
}

// Irrigation card
function IrrigationCard({ zone, data, onChange }: {
    zone: { name: string; drippers: number };
    data?: IrrigationCheckData;
    onChange: (data: IrrigationCheckData) => void;
}) {
    const [working, setWorking] = useState(data?.drippersWorking ?? zone.drippers);
    const [waterFlow, setWaterFlow] = useState(data?.waterFlow ?? true);
    const [nutrients, setNutrients] = useState(data?.nutrientsMixed ?? true);
    const [photo, setPhoto] = useState<string | null>(null);

    const handleSave = () => {
        onChange({
            zoneName: zone.name,
            drippersTotal: zone.drippers,
            drippersWorking: working,
            drippersFailed: [],
            waterFlow,
            nutrientsMixed: nutrients,
            scheduleActive: true,
            photoUrl: photo || undefined,
        });
    };

    if (data) {
        const issues = !data.waterFlow || !data.nutrientsMixed || data.drippersWorking < data.drippersTotal;
        return (
            <div className="flex items-center justify-between p-4 bg-tertiary rounded-lg">
                <div className="flex items-center gap-3">
                    <div className={cn("w-3 h-10 rounded-full", issues ? 'bg-warning' : 'bg-success')} />
                    <div>
                        <span className="text-sm font-medium text-primary">{zone.name}</span>
                        <p className="text-xs text-tertiary">{data.drippersWorking}/{data.drippersTotal} drippers</p>
                    </div>
                </div>
                <button
                    onClick={() => onChange(undefined as any)}
                    className="text-xs text-accent font-medium py-2 px-3"
                >
                    Edit
                </button>
            </div>
        );
    }

    return (
        <div className="p-4 bg-tertiary rounded-lg space-y-4">
            <span className="text-sm font-medium text-primary">{zone.name}</span>

            {/* Dripper counter - large touch targets */}
            <div className="flex items-center justify-center gap-6">
                <button
                    onClick={() => setWorking(Math.max(0, working - 1))}
                    className="w-14 h-14 bg-secondary rounded-xl flex items-center justify-center text-primary active:bg-tertiary"
                >
                    <Minus size={20} />
                </button>
                <div className="text-center">
                    <span className="text-3xl font-bold text-primary">{working}</span>
                    <span className="text-lg text-tertiary">/{zone.drippers}</span>
                    <p className="text-xs text-tertiary mt-1">drippers working</p>
                </div>
                <button
                    onClick={() => setWorking(Math.min(zone.drippers, working + 1))}
                    className="w-14 h-14 bg-secondary rounded-xl flex items-center justify-center text-primary active:bg-tertiary"
                >
                    <Plus size={20} />
                </button>
            </div>

            {/* Checkboxes - large touch targets */}
            <div className="grid grid-cols-2 gap-3">
                <label className={cn(
                    "flex items-center justify-center gap-2 p-4 rounded-xl cursor-pointer border-2 transition-colors",
                    waterFlow ? "bg-success/10 border-success text-success" : "bg-tertiary border-subtle text-tertiary"
                )}>
                    <input type="checkbox" checked={waterFlow} onChange={() => setWaterFlow(!waterFlow)} className="sr-only" />
                    <Check size={18} className={waterFlow ? "opacity-100" : "opacity-0"} />
                    <span className="text-sm font-medium">Flow OK</span>
                </label>
                <label className={cn(
                    "flex items-center justify-center gap-2 p-4 rounded-xl cursor-pointer border-2 transition-colors",
                    nutrients ? "bg-success/10 border-success text-success" : "bg-tertiary border-subtle text-tertiary"
                )}>
                    <input type="checkbox" checked={nutrients} onChange={() => setNutrients(!nutrients)} className="sr-only" />
                    <Check size={18} className={nutrients ? "opacity-100" : "opacity-0"} />
                    <span className="text-sm font-medium">Nutrients</span>
                </label>
            </div>

            <PhotoButton photoUrl={photo} onCapture={setPhoto} />

            <button onClick={handleSave} className="btn btn-primary w-full py-4">
                Save
            </button>
        </div>
    );
}

// Health card
function HealthCard({ zoneName, data, onChange }: {
    zoneName: string;
    data?: PlantHealthCheckData;
    onChange: (data: PlantHealthCheckData) => void;
}) {
    const [health, setHealth] = useState<'GOOD' | 'FAIR' | 'NEEDS_ATTENTION'>(data?.healthStatus ?? 'GOOD');
    const [pests, setPests] = useState(data?.pestsObserved ?? false);
    const [photo, setPhoto] = useState<string | null>(null);
    const [notes, setNotes] = useState('');

    const handleSave = () => {
        onChange({
            zoneName,
            healthStatus: health,
            pestsObserved: pests,
            waterAccess: 'OK',
            foodAccess: 'OK',
            flaggedForAttention: health !== 'GOOD' || pests,
            issuePhotoUrl: photo || undefined,
            notes: notes || undefined,
        });
    };

    if (data) {
        const color = data.healthStatus === 'GOOD' && !data.pestsObserved ? 'success' : data.healthStatus === 'FAIR' ? 'warning' : 'destructive';
        return (
            <div className="flex items-center justify-between p-4 bg-tertiary rounded-lg">
                <div className="flex items-center gap-3">
                    <div className={cn("w-3 h-10 rounded-full", `bg-${color}`)} />
                    <div>
                        <span className="text-sm font-medium text-primary">{zoneName}</span>
                        <p className="text-xs text-tertiary">
                            {data.healthStatus}{data.pestsObserved ? ' · 🐛 Pests' : ''}
                        </p>
                    </div>
                </div>
                <button
                    onClick={() => onChange(undefined as any)}
                    className="text-xs text-accent font-medium py-2 px-3"
                >
                    Edit
                </button>
            </div>
        );
    }

    return (
        <div className="p-4 bg-tertiary rounded-lg space-y-4">
            <span className="text-sm font-medium text-primary">{zoneName}</span>

            {/* Health - large touch targets */}
            <div className="grid grid-cols-3 gap-2">
                {(['GOOD', 'FAIR', 'NEEDS_ATTENTION'] as const).map(s => (
                    <button
                        key={s}
                        onClick={() => setHealth(s)}
                        className={cn(
                            "py-4 rounded-xl text-sm font-medium border-2 transition-all",
                            health === s ? (
                                s === 'GOOD' ? 'bg-success/10 border-success text-success' :
                                    s === 'FAIR' ? 'bg-warning/10 border-warning text-warning' :
                                        'bg-destructive/10 border-destructive text-destructive'
                            ) : 'bg-secondary border-subtle text-tertiary'
                        )}
                    >
                        {s === 'GOOD' ? '✓ Good' : s === 'FAIR' ? '⚠ Fair' : '✕ Bad'}
                    </button>
                ))}
            </div>

            {/* Pests */}
            <label className={cn(
                "flex items-center justify-center gap-3 p-4 rounded-xl cursor-pointer border-2 transition-colors",
                pests ? "bg-destructive/10 border-destructive text-destructive" : "bg-tertiary border-subtle text-tertiary"
            )}>
                <input type="checkbox" checked={pests} onChange={() => setPests(!pests)} className="sr-only" />
                <span className="text-lg">🐛</span>
                <span className="text-sm font-medium">Pests Observed</span>
            </label>

            {/* Notes + Photo for issues */}
            {(health !== 'GOOD' || pests) && (
                <>
                    <VoiceInput value={notes} onChange={setNotes} placeholder="Describe issue..." />
                    <PhotoButton photoUrl={photo} onCapture={setPhoto} />
                </>
            )}

            <button onClick={handleSave} className="btn btn-primary w-full py-4">
                Save
            </button>
        </div>
    );
}
