import { useState } from 'react';
import { X, Search, AlertTriangle, Check } from 'lucide-react';
import { Batch } from '../../lib/batchesApi';
import { touchPointsApi } from '../../lib/touchPointsApi';

interface ScoutingModalProps {
    batch: Batch;
    onClose: () => void;
    onSuccess: () => void;
}

export default function ScoutingModal({ batch, onClose, onSuccess }: ScoutingModalProps) {
    const [notes, setNotes] = useState('');
    const [issuesObserved, setIssuesObserved] = useState(false);
    const [issueType, setIssueType] = useState('Pests');
    const [severity, setSeverity] = useState<'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'>('LOW');
    const [photoUrl, setPhotoUrl] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            await touchPointsApi.create({
                batchId: batch.id,
                type: 'INSPECT',
                notes: `${severity} Severity. ${notes}`,
                issuesObserved,
                issueType: issuesObserved ? issueType : undefined,
                photoUrls: photoUrl ? [photoUrl] : [],
            });
            onSuccess();
            onClose();
        } catch (error) {
            console.error('Failed to log scouting report', error);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-in">
            <div className="bg-elevated w-full max-w-md rounded-lg shadow-xl border border-default overflow-hidden animate-scale-in">
                {/* Header */}
                <div className="px-5 py-4 border-b border-default flex justify-between items-center">
                    <h2 className="text-lg font-semibold text-primary flex items-center gap-2">
                        <Search size={18} className="text-accent" />
                        Scout Batch
                    </h2>
                    <button onClick={onClose} className="p-2 hover:bg-tertiary rounded-md transition-colors duration-fast">
                        <X size={16} className="text-secondary" />
                    </button>
                </div>

                {/* Batch Info */}
                <div className="px-5 py-3 bg-tertiary border-b border-subtle">
                    <h3 className="font-medium text-primary text-sm">{batch.name}</h3>
                    <p className="text-xs text-tertiary">{batch.strain}</p>
                </div>

                <form onSubmit={handleSubmit} className="p-5 space-y-5">
                    {/* Issues Toggle */}
                    <button
                        type="button"
                        onClick={() => setIssuesObserved(!issuesObserved)}
                        className={`w-full flex items-center justify-between p-4 rounded-md border transition-colors duration-fast ${issuesObserved
                                ? 'bg-destructive-muted border-destructive/30'
                                : 'bg-success-muted border-success/30'
                            }`}
                    >
                        <div className="flex items-center gap-3">
                            <AlertTriangle size={18} className={issuesObserved ? 'text-destructive' : 'text-success'} />
                            <span className="font-medium text-primary">Issues Observed?</span>
                        </div>
                        <div className={`w-6 h-6 rounded-md flex items-center justify-center ${issuesObserved ? 'bg-destructive text-white' : 'bg-success text-white'
                            }`}>
                            {issuesObserved ? '!' : <Check size={14} />}
                        </div>
                    </button>

                    {issuesObserved && (
                        <div className="grid grid-cols-2 gap-4 animate-in">
                            <div>
                                <label className="block text-sm font-medium text-secondary mb-1.5">Issue Type</label>
                                <select
                                    value={issueType}
                                    onChange={(e) => setIssueType(e.target.value)}
                                    className="input w-full"
                                >
                                    <option value="Pests">Pests</option>
                                    <option value="Disease">Disease</option>
                                    <option value="Nutrient">Nutrient Deficiency</option>
                                    <option value="Environment">Environmental Stress</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-secondary mb-1.5">Severity</label>
                                <select
                                    value={severity}
                                    onChange={(e) => setSeverity(e.target.value as any)}
                                    className="input w-full"
                                >
                                    <option value="LOW">Low</option>
                                    <option value="MEDIUM">Medium</option>
                                    <option value="HIGH">High</option>
                                    <option value="CRITICAL">Critical</option>
                                </select>
                            </div>
                        </div>
                    )}

                    <div>
                        <label className="block text-sm font-medium text-secondary mb-1.5">Observations / Notes</label>
                        <textarea
                            value={notes}
                            onChange={(e) => setNotes(e.target.value)}
                            className="input w-full resize-none"
                            rows={3}
                            placeholder="Describe what you see..."
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-secondary mb-1.5">Photo URL (Optional)</label>
                        <input
                            type="text"
                            value={photoUrl}
                            onChange={(e) => setPhotoUrl(e.target.value)}
                            className="input w-full"
                            placeholder="https://..."
                        />
                    </div>

                    <div className="flex gap-3 pt-2">
                        <button type="button" onClick={onClose} className="btn btn-secondary flex-1">
                            Cancel
                        </button>
                        <button
                            type="submit"
                            disabled={isSubmitting}
                            className={`btn flex-1 ${issuesObserved ? 'bg-destructive hover:bg-destructive/90' : 'btn-primary'} text-white`}
                        >
                            <Search size={16} />
                            Submit Report
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}
