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,
    Camera, X, Minus, Plus, ChevronDown, ChevronUp, Upload, CheckCircle, Clock
} from 'lucide-react';
import { useToast } from '../context/ToastContext';

// Tank/Zone configs
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: true,
        plantHealth: true,
    });

    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 {
            // Submit all checks
            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 - show success state
    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-4">
                <div className="w-full max-w-sm text-center">
                    <div className="w-24 h-24 mx-auto mb-6 rounded-full bg-success/20 flex items-center justify-center">
                        <CheckCircle size={48} className="text-success" />
                    </div>
                    <h1 className="text-xl font-semibold text-primary mb-2">Walkthrough Complete!</h1>
                    <p className="text-sm text-tertiary mb-2">
                        {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
                    </p>
                    <div className="bg-success/10 border border-success/20 rounded-lg p-4 mb-6">
                        <div className="flex items-center justify-center gap-2 text-success">
                            <Clock size={16} />
                            <span className="text-sm font-medium">
                                Completed at {completedTime.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                            </span>
                        </div>
                        <p className="text-xs text-tertiary mt-1">
                            by {todaysWalkthrough.user?.name || 'Unknown'}
                        </p>
                    </div>
                    <Link to="/" className="btn btn-primary w-full text-base py-3">
                        Back to Dashboard
                    </Link>
                    <button
                        onClick={() => { setTodaysWalkthrough(null); }}
                        className="block w-full mt-4 text-sm text-tertiary hover:text-secondary"
                    >
                        Start a new walkthrough anyway
                    </button>
                </div>
            </div>
        );
    }

    // In-progress walkthrough from earlier
    if (todaysWalkthrough?.status === 'IN_PROGRESS' && !walkthroughId) {
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center p-4">
                <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={36} 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 at {new Date(todaysWalkthrough.startTime).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                    </p>
                    <button
                        onClick={() => setWalkthroughId(todaysWalkthrough.id)}
                        className="btn btn-primary w-full text-base py-3"
                    >
                        Continue Walkthrough
                    </button>
                    <Link to="/" className="block mt-4 text-sm text-tertiary hover:text-secondary">
                        ← Back to Dashboard
                    </Link>
                </div>
            </div>
        );
    }

    // Pre-start view
    if (!walkthroughId) {
        return (
            <div className="min-h-screen bg-primary flex items-center justify-center p-4">
                <div className="w-full max-w-sm 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-xl font-semibold text-primary mb-2">Daily Walkthrough</h1>
                    <p className="text-sm text-tertiary mb-6">
                        {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
                    </p>
                    <button
                        onClick={handleStart}
                        disabled={isStarting}
                        className="btn btn-primary w-full text-base py-3"
                    >
                        {isStarting ? <Loader2 size={18} className="animate-spin" /> : 'Begin Walkthrough'}
                    </button>
                    <Link to="/" className="block mt-4 text-sm text-tertiary hover:text-secondary">
                        ← Back to Dashboard
                    </Link>
                </div>
            </div>
        );
    }


    return (
        <div className="max-w-2xl mx-auto pb-28 animate-in">

            {/* Header with Progress */}
            <div className="card p-4 mb-4">
                <div className="flex items-center justify-between mb-3">
                    <div>
                        <h1 className="text-lg font-semibold text-primary">Daily Walkthrough</h1>
                        <p className="text-xs text-tertiary">
                            {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
                        </p>
                    </div>
                    <div className="text-right">
                        <span className="text-2xl font-bold text-accent">{progressPercent}%</span>
                        <p className="text-xs text-tertiary">{totalChecks}/{requiredChecks} checks</p>
                    </div>
                </div>
                {/* Progress bar */}
                <div className="h-2 bg-subtle rounded-full overflow-hidden">
                    <div
                        className="h-full bg-accent transition-all duration-500 ease-out"
                        style={{ width: `${progressPercent}%` }}
                    />
                </div>
            </div>

            {/* Sections */}
            <div className="space-y-3">
                {/* Reservoirs Section */}
                {settings?.enableReservoirs !== false && (
                    <CollapsibleSection
                        title="Reservoirs"
                        icon={Droplets}
                        count={Object.keys(reservoirChecks).length}
                        total={TANKS.length}
                        expanded={expandedSections.reservoirs}
                        onToggle={() => toggleSection('reservoirs')}
                    >
                        <div className="space-y-2">
                            {TANKS.map(tank => (
                                <ReservoirRow
                                    key={tank.name}
                                    tank={tank}
                                    data={reservoirChecks[tank.name]}
                                    onChange={(data) => setReservoirChecks(prev => ({ ...prev, [tank.name]: data }))}
                                />
                            ))}
                        </div>
                    </CollapsibleSection>
                )}

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

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

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

// Collapsible Section
function CollapsibleSection({
    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 isComplete = 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"
            >
                <div className="flex items-center gap-3">
                    <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${isComplete ? 'bg-success-muted text-success' : 'bg-accent-muted text-accent'
                        }`}>
                        {isComplete ? <Check size={18} /> : <Icon size={18} />}
                    </div>
                    <div className="text-left">
                        <h3 className="text-sm font-medium text-primary">{title}</h3>
                        <p className="text-xs text-tertiary">{count}/{total} complete</p>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {isComplete && <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>
    );
}

// Inline Photo Capture Component
function PhotoCapture({
    onCapture,
    photoUrl
}: {
    onCapture: (url: string | null) => void;
    photoUrl?: string | null;
}) {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const cameraInputRef = useRef<HTMLInputElement>(null);

    const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            // For now, create a local preview URL
            // In production, this would upload to server
            const url = URL.createObjectURL(file);
            onCapture(url);
        }
    };

    if (photoUrl) {
        return (
            <div className="relative mt-2">
                <img src={photoUrl} alt="Captured" 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 (
        <div className="flex gap-2 mt-2">
            <input ref={fileInputRef} type="file" accept="image/*" onChange={handleFile} className="hidden" />
            <input ref={cameraInputRef} type="file" accept="image/*" capture="environment" onChange={handleFile} className="hidden" />

            <button
                type="button"
                onClick={() => cameraInputRef.current?.click()}
                className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-accent text-white rounded-lg text-xs font-medium hover:bg-accent/90 transition-colors"
            >
                <Camera size={14} />
                Camera
            </button>
            <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-subtle text-secondary rounded-lg text-xs font-medium hover:bg-secondary transition-colors"
            >
                <Upload size={14} />
                Upload
            </button>
        </div>
    );
}

// Reservoir Row - Enhanced with photo
function ReservoirRow({
    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 [editing, setEditing] = useState(!data);

    const getStatus = (l: number) => l >= 70 ? 'OK' : l >= 30 ? 'LOW' : 'CRITICAL';

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

    if (!editing && data) {
        return (
            <div className="flex items-center justify-between p-3 bg-tertiary rounded-lg">
                <div className="flex items-center gap-3">
                    <div className={`w-2 h-10 rounded-full ${data.status === 'OK' ? 'bg-success' : data.status === 'LOW' ? 'bg-warning' : 'bg-destructive'
                        }`} />
                    <div>
                        <span className="text-sm font-medium text-primary">{tank.name}</span>
                        <div className="flex items-center gap-2">
                            <span className="text-xs text-tertiary">{data.levelPercent}%</span>
                            {data.photoUrl && <Camera size={10} className="text-accent" />}
                        </div>
                    </div>
                </div>
                <button onClick={() => setEditing(true)} className="text-xs text-accent font-medium">Edit</button>
            </div>
        );
    }

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

            {/* Level Slider */}
            <div className="flex items-center gap-3">
                <div className={`w-4 h-14 rounded-full overflow-hidden bg-subtle relative`}>
                    <div
                        className={`absolute bottom-0 left-0 right-0 transition-all ${getStatus(level) === 'OK' ? 'bg-success' : getStatus(level) === 'LOW' ? 'bg-warning' : 'bg-destructive'}`}
                        style={{ height: `${level}%` }}
                    />
                </div>
                <div className="flex-1">
                    <input
                        type="range"
                        min="0"
                        max="100"
                        value={level}
                        onChange={(e) => setLevel(parseInt(e.target.value))}
                        className="w-full h-2 bg-subtle rounded-full appearance-none cursor-pointer"
                    />
                </div>
                <span className={`text-lg font-bold w-14 text-right ${getStatus(level) === 'OK' ? 'text-success' : getStatus(level) === 'LOW' ? 'text-warning' : 'text-destructive'}`}>
                    {level}%
                </span>
            </div>

            {/* Notes */}
            <input
                type="text"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Notes (optional)"
                className="w-full px-3 py-2 bg-primary border border-subtle rounded-lg text-sm"
            />

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

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

// Irrigation Row - Enhanced with photo
function IrrigationRow({
    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 [editing, setEditing] = useState(!data);

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

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

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

            {/* Dripper Count */}
            <div className="flex items-center justify-center gap-4">
                <button
                    onClick={() => setWorking(Math.max(0, working - 1))}
                    className="w-10 h-10 bg-subtle rounded-lg flex items-center justify-center hover:bg-secondary transition-colors"
                >
                    <Minus size={16} />
                </button>
                <div className="text-center">
                    <span className="text-2xl font-bold text-primary">{working}</span>
                    <span className="text-sm text-tertiary">/{zone.drippers}</span>
                    <p className="text-xs text-tertiary">drippers working</p>
                </div>
                <button
                    onClick={() => setWorking(Math.min(zone.drippers, working + 1))}
                    className="w-10 h-10 bg-subtle rounded-lg flex items-center justify-center hover:bg-secondary transition-colors"
                >
                    <Plus size={16} />
                </button>
            </div>

            {/* Checkboxes */}
            <div className="flex items-center justify-center gap-6">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input
                        type="checkbox"
                        checked={waterFlow}
                        onChange={() => setWaterFlow(!waterFlow)}
                        className="w-5 h-5 rounded accent-accent"
                    />
                    Water Flow
                </label>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input
                        type="checkbox"
                        checked={nutrients}
                        onChange={() => setNutrients(!nutrients)}
                        className="w-5 h-5 rounded accent-accent"
                    />
                    Nutrients
                </label>
            </div>

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

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

// Plant Health Row - Enhanced with photo
function PlantHealthRow({
    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 [editing, setEditing] = useState(!data);

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

    if (!editing && data) {
        return (
            <div className="flex items-center justify-between p-3 bg-tertiary rounded-lg">
                <div className="flex items-center gap-3">
                    <div className={`w-2 h-10 rounded-full ${data.healthStatus === 'GOOD' && !data.pestsObserved ? 'bg-success' :
                        data.healthStatus === 'FAIR' ? 'bg-warning' : 'bg-destructive'
                        }`} />
                    <div>
                        <span className="text-sm font-medium text-primary">{zoneName}</span>
                        <div className="flex items-center gap-2">
                            <span className={`text-xs ${data.healthStatus === 'GOOD' ? 'text-success' : data.healthStatus === 'FAIR' ? 'text-warning' : 'text-destructive'}`}>
                                {data.healthStatus}
                            </span>
                            {data.pestsObserved && <span className="text-xs text-destructive">🐛</span>}
                            {data.issuePhotoUrl && <Camera size={10} className="text-accent" />}
                        </div>
                    </div>
                </div>
                <button onClick={() => setEditing(true)} className="text-xs text-accent font-medium">Edit</button>
            </div>
        );
    }

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

            {/* Health Status Buttons */}
            <div className="grid grid-cols-3 gap-2">
                {(['GOOD', 'FAIR', 'NEEDS_ATTENTION'] as const).map(s => (
                    <button
                        key={s}
                        onClick={() => setHealth(s)}
                        className={`py-3 rounded-lg text-sm font-medium transition-all ${health === s
                            ? s === 'GOOD' ? 'bg-success text-white shadow-lg scale-105'
                                : s === 'FAIR' ? 'bg-warning text-white shadow-lg scale-105'
                                    : 'bg-destructive text-white shadow-lg scale-105'
                            : 'bg-subtle text-secondary hover:bg-secondary'
                            }`}
                    >
                        {s === 'GOOD' ? '✓ Good' : s === 'FAIR' ? '⚠️ Fair' : '❌ Attention'}
                    </button>
                ))}
            </div>

            {/* Pests Checkbox */}
            <label className="flex items-center justify-center gap-2 p-3 bg-destructive-muted rounded-lg cursor-pointer">
                <input
                    type="checkbox"
                    checked={pests}
                    onChange={() => setPests(!pests)}
                    className="w-5 h-5 rounded accent-destructive"
                />
                <span className="text-sm text-destructive font-medium">🐛 Pests Observed</span>
            </label>

            {/* Notes */}
            {(health !== 'GOOD' || pests) && (
                <input
                    type="text"
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    placeholder="Describe the issue..."
                    className="w-full px-3 py-2 bg-primary border border-subtle rounded-lg text-sm"
                />
            )}

            {/* Photo Capture - shown for issues */}
            {(health !== 'GOOD' || pests) && (
                <>
                    <p className="text-xs text-tertiary text-center">📷 Photo recommended for issues</p>
                    <PhotoCapture photoUrl={photo} onCapture={setPhoto} />
                </>
            )}

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