import { useState, useEffect } from 'react';
import { X, Save, Calendar as CalendarIcon, User, MapPin, Box, FileText } from 'lucide-react';
import { tasksApi, CreateTaskData } from '../../lib/tasksApi';
import { taskTemplatesApi, TaskTemplate } from '../../lib/taskTemplatesApi';
import { usersApi, User as ApiUser } from '../../lib/usersApi';
import { useToast } from '../../context/ToastContext';
import api from '../../lib/api';

interface CreateTaskModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess?: () => void;
    initialBatchId?: string;
    initialRoomId?: string;
}

export default function CreateTaskModal({
    isOpen,
    onClose,
    onSuccess,
    initialBatchId,
    initialRoomId
}: CreateTaskModalProps) {
    const { addToast } = useToast();
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [priority, setPriority] = useState('MEDIUM');
    const [dueDate, setDueDate] = useState(new Date().toISOString().split('T')[0]);

    // Selection Data
    const [users, setUsers] = useState<ApiUser[]>([]);
    const [rooms, setRooms] = useState<any[]>([]);
    const [batches, setBatches] = useState<any[]>([]);
    const [templates, setTemplates] = useState<TaskTemplate[]>([]);

    // Selected Values
    const [assigneeId, setAssigneeId] = useState('');
    const [roomId, setRoomId] = useState(initialRoomId || '');
    const [batchId, setBatchId] = useState(initialBatchId || '');
    const [selectedTemplateId, setSelectedTemplateId] = useState('');

    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        if (isOpen) {
            setRoomId(initialRoomId || '');
            setBatchId(initialBatchId || '');

            Promise.all([
                usersApi.getAll(),
                api.get('/rooms').then(r => r.data),
                api.get('/batches').then(r => r.data),
                taskTemplatesApi.getAll()
            ]).then(([usersData, roomsData, batchesData, templatesData]) => {
                setUsers(usersData);
                setRooms(roomsData);
                setBatches(batchesData);
                setTemplates(templatesData);
            }).catch(err => {
                console.error(err);
                addToast('Failed to load form data', 'error');
            });
        }
    }, [isOpen, initialBatchId, initialRoomId]);

    const handleTemplateChange = (templateId: string) => {
        setSelectedTemplateId(templateId);
        if (!templateId) return;

        const template = templates.find(t => t.id === templateId);
        if (template) {
            setTitle(template.title);
            let desc = template.description || '';
            if (template.materials && template.materials.length > 0) {
                desc += `\n\nMaterials:\n- ${template.materials.join('\n- ')}`;
            }
            setDescription(desc);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsLoading(true);
        try {
            const payload: CreateTaskData = {
                title,
                description,
                priority,
                dueDate,
                assigneeId: assigneeId || undefined,
                roomId: roomId || undefined,
                batchId: batchId || undefined,
            };

            await tasksApi.create(payload);
            onSuccess?.();
            onClose();
            // Reset form
            setTitle('');
            setDescription('');
            setPriority('MEDIUM');
            setAssigneeId('');
            setRoomId('');
            setBatchId('');
            setSelectedTemplateId('');
        } catch (error) {
            console.error('Failed to create task', error);
            addToast('Failed to create task. Please try again.', 'error');
        } finally {
            setIsLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm animate-in fade-in duration-200">
            <div className="bg-[var(--color-bg-elevated)] w-full max-w-lg rounded-2xl shadow-xl overflow-hidden flex flex-col max-h-[90vh]">

                <div className="p-4 border-b border-[var(--color-border-subtle)] flex justify-between items-center">
                    <h2 className="text-xl font-bold text-[var(--color-text-primary)]">New Task</h2>
                    <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full">
                        <X size={20} className="text-[var(--color-text-tertiary)]" />
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">

                    {/* Template Selection */}
                    <div className="bg-[var(--color-bg-tertiary)]/50 p-3 rounded-xl border border-dashed border-slate-300 dark:border-slate-700">
                        <label className="block text-xs font-bold text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2 flex items-center gap-2">
                            <FileText size={14} /> Quick Fill from Template
                        </label>
                        <select
                            value={selectedTemplateId}
                            onChange={(e) => handleTemplateChange(e.target.value)}
                            className="w-full p-2 bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] rounded-lg text-sm text-[var(--color-text-primary)]"
                        >
                            <option value="">-- Start Blank --</option>
                            {templates.map(t => (
                                <option key={t.id} value={t.id}>{t.title} ({t.roomType})</option>
                            ))}
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-bold text-[var(--color-text-secondary)] mb-1">Task Title *</label>
                        <input
                            required
                            value={title}
                            onChange={e => setTitle(e.target.value)}
                            placeholder="e.g. Water Room A"
                            className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)] focus:ring-2 focus:ring-emerald-500"
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1">Priority</label>
                            <select
                                value={priority}
                                onChange={e => setPriority(e.target.value)}
                                className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)]"
                            >
                                <option value="LOW">Low</option>
                                <option value="MEDIUM">Medium</option>
                                <option value="HIGH">High</option>
                                <option value="URGENT">Urgent</option>
                            </select>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1">Due Date</label>
                            <input
                                type="date"
                                required
                                value={dueDate}
                                onChange={e => setDueDate(e.target.value)}
                                className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)]"
                            />
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1 flex items-center gap-2">
                            <User size={16} /> Assign To
                        </label>
                        <select
                            value={assigneeId}
                            onChange={e => setAssigneeId(e.target.value)}
                            className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)]"
                        >
                            <option value="">-- Unassigned --</option>
                            {users.map(u => (
                                <option key={u.id} value={u.id}>{u.name || u.email} ({u.role})</option>
                            ))}
                        </select>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1 flex items-center gap-2">
                                <MapPin size={16} /> Room (Optional)
                            </label>
                            <select
                                value={roomId}
                                onChange={e => setRoomId(e.target.value)}
                                className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)]"
                            >
                                <option value="">-- None --</option>
                                {rooms.map(r => (
                                    <option key={r.id} value={r.id}>{r.name} ({r.type})</option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1 flex items-center gap-2">
                                <Box size={16} /> Batch (Optional)
                            </label>
                            <select
                                value={batchId}
                                onChange={e => setBatchId(e.target.value)}
                                className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)]"
                            >
                                <option value="">-- None --</option>
                                {batches.map(b => (
                                    <option key={b.id} value={b.id}>{b.name}</option>
                                ))}
                            </select>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-1">Description / Notes</label>
                        <textarea
                            value={description}
                            onChange={e => setDescription(e.target.value)}
                            rows={3}
                            placeholder="Details about the task..."
                            className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)] resize-none"
                        />
                    </div>

                    <button
                        type="submit"
                        disabled={isLoading}
                        className="w-full py-4 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] disabled:opacity-50 text-white font-bold rounded-xl flex items-center justify-center gap-2 mt-4"
                    >
                        {isLoading ? 'Creating...' : (
                            <>
                                <Save size={20} />
                                <span>Create Task</span>
                            </>
                        )}
                    </button>
                </form>
            </div>
        </div>
    );
}
