import { useState } from 'react';
import { ArrowLeft, ChevronRight, Camera, X, Check, Bug } from 'lucide-react';

interface PlantHealthCheckData {
    zoneName: string;
    healthStatus: 'GOOD' | 'FAIR' | 'NEEDS_ATTENTION';
    pestsObserved: boolean;
    pestType?: string;
    waterAccess: 'OK' | 'ISSUES';
    foodAccess: 'OK' | 'ISSUES';
    flaggedForAttention: boolean;
    issuePhotoUrl?: string;
    referencePhotoUrl?: string;
    notes?: string;
}

interface PlantHealthChecklistProps {
    onComplete: (checks: PlantHealthCheckData[]) => void;
    onBack: () => void;
    isPhotoRequired: boolean;
}

export default function PlantHealthChecklist({ onComplete, onBack, isPhotoRequired }: PlantHealthChecklistProps) {
    const zones = ['Veg Upstairs', 'Veg Downstairs', 'Flower Upstairs', 'Flower Downstairs'];

    const [checks, setChecks] = useState<Map<string, PlantHealthCheckData>>(new Map());
    const [currentZoneIndex, setCurrentZoneIndex] = useState(0);
    const [healthStatus, setHealthStatus] = useState<'GOOD' | 'FAIR' | 'NEEDS_ATTENTION'>('GOOD');
    const [pestsObserved, setPestsObserved] = useState(false);
    const [pestType, setPestType] = useState('');
    const [waterAccess, setWaterAccess] = useState<'OK' | 'ISSUES'>('OK');
    const [foodAccess, setFoodAccess] = useState<'OK' | 'ISSUES'>('OK');
    const [notes, setNotes] = useState('');
    const [referencePhoto, setReferencePhoto] = useState<string | null>(null);

    const currentZone = zones[currentZoneIndex];
    const isLastZone = currentZoneIndex === zones.length - 1;
    const hasIssues = healthStatus !== 'GOOD' || pestsObserved || waterAccess === 'ISSUES' || foodAccess === 'ISSUES';

    const handleNext = () => {
        if (isPhotoRequired && !referencePhoto) {
            alert('Reference photo is required for this step.');
            return;
        }

        const checkData: PlantHealthCheckData = {
            zoneName: currentZone,
            healthStatus,
            pestsObserved,
            pestType: pestsObserved ? pestType : undefined,
            waterAccess,
            foodAccess,
            flaggedForAttention: hasIssues,
            notes: notes || undefined,
            referencePhotoUrl: referencePhoto || undefined,
        };

        const newChecks = new Map(checks);
        newChecks.set(currentZone, checkData);
        setChecks(newChecks);

        if (isLastZone) {
            onComplete(Array.from(newChecks.values()));
        } else {
            setCurrentZoneIndex(currentZoneIndex + 1);
            setHealthStatus('GOOD');
            setPestsObserved(false);
            setPestType('');
            setWaterAccess('OK');
            setFoodAccess('OK');
            setNotes('');
            setReferencePhoto(null);
        }
    };

    return (
        <div className="min-h-screen bg-primary flex items-center justify-center p-4">
            <div className="w-full max-w-sm">
                {/* Header */}
                <div className="flex items-center gap-3 mb-6">
                    <button onClick={onBack} className="p-2 -ml-2 hover:bg-tertiary rounded-md transition-colors">
                        <ArrowLeft size={16} className="text-secondary" />
                    </button>
                    <div className="flex-1">
                        <p className="text-xs text-tertiary">Zone {currentZoneIndex + 1}/{zones.length}</p>
                        <h1 className="text-lg font-semibold text-primary">{currentZone}</h1>
                    </div>
                </div>

                {/* Progress */}
                <div className="flex gap-1 mb-6">
                    {zones.map((_, i) => (
                        <div
                            key={i}
                            className={`h-1 flex-1 rounded-full ${i <= currentZoneIndex ? 'bg-accent' : 'bg-tertiary'}`}
                        />
                    ))}
                </div>

                {/* Health Status - compact segmented control */}
                <div className="card p-4 mb-4">
                    <p className="text-xs text-tertiary mb-2">Overall Health</p>
                    <div className="flex gap-2">
                        {(['GOOD', 'FAIR', 'NEEDS_ATTENTION'] as const).map(status => (
                            <button
                                key={status}
                                onClick={() => setHealthStatus(status)}
                                className={`flex-1 py-2 rounded-md text-xs font-medium transition-colors ${healthStatus === status
                                        ? status === 'GOOD' ? 'bg-success text-white'
                                            : status === 'FAIR' ? 'bg-warning text-white'
                                                : 'bg-destructive text-white'
                                        : 'bg-tertiary text-secondary hover:bg-secondary'
                                    }`}
                            >
                                {status === 'NEEDS_ATTENTION' ? 'Attention' : status.charAt(0) + status.slice(1).toLowerCase()}
                            </button>
                        ))}
                    </div>
                </div>

                {/* Pest Check */}
                <div className="card divide-y divide-subtle mb-4">
                    <button
                        onClick={() => setPestsObserved(!pestsObserved)}
                        className="w-full flex items-center justify-between px-4 py-3"
                    >
                        <div className="flex items-center gap-2">
                            <Bug size={14} className={pestsObserved ? 'text-destructive' : 'text-tertiary'} />
                            <span className="text-sm text-primary">Pests Observed</span>
                        </div>
                        <div className={`w-5 h-5 rounded flex items-center justify-center ${pestsObserved ? 'bg-destructive text-white' : 'bg-success text-white'
                            }`}>
                            {pestsObserved ? '!' : <Check size={12} />}
                        </div>
                    </button>
                    {pestsObserved && (
                        <div className="px-4 py-3">
                            <input
                                type="text"
                                value={pestType}
                                onChange={(e) => setPestType(e.target.value)}
                                placeholder="Type of pest..."
                                className="input w-full text-sm"
                            />
                        </div>
                    )}
                </div>

                {/* Access Status */}
                <div className="card divide-y divide-subtle mb-4">
                    <StatusRow
                        label="Water Access"
                        value={waterAccess === 'OK'}
                        onChange={(v) => setWaterAccess(v ? 'OK' : 'ISSUES')}
                    />
                    <StatusRow
                        label="Nutrient Access"
                        value={foodAccess === 'OK'}
                        onChange={(v) => setFoodAccess(v ? 'OK' : 'ISSUES')}
                    />
                </div>

                {/* Notes - only if issues */}
                {hasIssues && (
                    <div className="mb-4">
                        <input
                            type="text"
                            value={notes}
                            onChange={(e) => setNotes(e.target.value)}
                            placeholder="Notes..."
                            className="input w-full text-sm"
                        />
                    </div>
                )}

                {/* Photo */}
                {(isPhotoRequired || hasIssues) && (
                    <div className="mb-4">
                        <input type="file" id="photo-upload" className="hidden" accept="image/*" capture="environment"
                            onChange={(e) => { if (e.target.files?.[0]) setReferencePhoto(URL.createObjectURL(e.target.files[0])); }} />
                        {referencePhoto ? (
                            <div className="relative">
                                <img src={referencePhoto} alt="Preview" className="w-full h-24 object-cover rounded-md" />
                                <button onClick={() => setReferencePhoto(null)} className="absolute top-1 right-1 p-1 bg-black/50 rounded-full">
                                    <X size={12} className="text-white" />
                                </button>
                            </div>
                        ) : (
                            <label htmlFor="photo-upload" className={`flex items-center justify-center gap-2 p-3 border border-dashed rounded-md cursor-pointer text-sm ${isPhotoRequired ? 'border-destructive/50 text-destructive' : 'border-subtle text-tertiary'
                                }`}>
                                <Camera size={14} />
                                {isPhotoRequired ? 'Photo required' : 'Add photo'}
                            </label>
                        )}
                    </div>
                )}

                {/* Action */}
                <button onClick={handleNext} className="btn btn-primary w-full">
                    {isLastZone ? 'Complete' : 'Next'}
                    {!isLastZone && <ChevronRight size={14} />}
                </button>
            </div>
        </div>
    );
}

function StatusRow({ label, value, onChange }: { label: string; value: boolean; onChange: (v: boolean) => void }) {
    return (
        <button
            onClick={() => onChange(!value)}
            className="w-full flex items-center justify-between px-4 py-3 hover:bg-tertiary transition-colors"
        >
            <span className="text-sm text-primary">{label}</span>
            <div className={`w-5 h-5 rounded flex items-center justify-center ${value ? 'bg-success text-white' : 'bg-destructive text-white'
                }`}>
                {value ? <Check size={12} /> : <X size={12} />}
            </div>
        </button>
    );
}
