import React, { useState, useEffect } from 'react';
import { API } from '../../api/API';
import { toast } from 'sonner';
import { Trash2, Plus, Save, AlertCircle, ArrowLeft } from 'lucide-react';
import { useParams, useNavigate } from 'react-router-dom';

interface Question {
    id?: string;
    sectionName: string;
    questionText: string;
    inputType: 'text' | 'yesno' | 'file' | 'number' | 'select' | 'mcq' | 'radio' | 'textarea' | 'email';
    options?: { text: string; score: number }[];
    weight: number;
    order: number;
    isMandatory: boolean;
}

const SECTIONS = [
    'Personal Information',
    'Financial Information',
    'Location & Background',
    'Motivation',
    'Business Structure',
    'Professional Background',
    'Infrastructure',
    'Financial Planning',
    'Growth & Expansion',
    'Brand Affinity',
    'Vision & Strategy'
];

const QuestionnaireBuilder: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const [version, setVersion] = useState<string>(`v${new Date().toISOString().split('T')[0]}`);
    const [questions, setQuestions] = useState<Question[]>([
        { sectionName: 'Personal Information', questionText: '', inputType: 'text', weight: 0, order: 1, isMandatory: true }
    ]);
    const [loading, setLoading] = useState(false);
    const [fetching, setFetching] = useState(!!id);

    useEffect(() => {
        if (id) {
            fetchQuestionnaire(id);
        }
    }, [id]);

    const fetchQuestionnaire = async (questionnaireId: string) => {
        try {
            setFetching(true);
            const response = await API.getQuestionnaireById(questionnaireId) as any;
            if (response.data?.success) {
                const data = response.data.data;
                setVersion(`${data.version} (Copy)`); // Default to making a copy
                if (data.questions && data.questions.length > 0) {
                    setQuestions(data.questions.map((q: any) => {
                        let normalizedType = q.inputType?.toLowerCase().trim();
                        if (normalizedType === 'mcq') normalizedType = 'select';

                        // Fallback validity check
                        const validTypes = ['text', 'number', 'file', 'yesno', 'select', 'radio', 'textarea', 'email', 'mcq'];
                        if (!validTypes.includes(normalizedType)) normalizedType = 'text';

                        return {
                            ...q,
                            inputType: normalizedType,
                            weight: parseFloat(q.weight), // Ensure weight is number
                            options: q.questionOptions?.map((opt: any) => ({ text: opt.optionText, score: opt.score })) || []
                        };
                    }));
                }
            } else {
                toast.error('Failed to load questionnaire');
                navigate('/questionnaires');
            }
        } catch (error) {
            console.error(error);
            toast.error('Error fetching questionnaire');
        } finally {
            setFetching(false);
        }
    };

    const totalWeight = questions.reduce((sum, q) => sum + (q.weight || 0), 0);

    const addQuestion = () => {
        setQuestions([...questions, {
            sectionName: 'Personal Information',
            questionText: '',
            inputType: 'text',
            weight: 0,
            order: questions.length + 1,
            isMandatory: true
        }]);
    };

    const removeQuestion = (index: number) => {
        const newQuestions = questions.filter((_, i) => i !== index);
        // Re-order
        const reOrdered = newQuestions.map((q, i) => ({ ...q, order: i + 1 }));
        setQuestions(reOrdered);
    };

    const updateQuestion = (index: number, field: keyof Question, value: any) => {
        const newQuestions = [...questions];

        // Weight validation and option score capping
        if (field === 'weight') {
            const newWeight = parseFloat(value) || 0;
            // Cap existing option scores if weight is decreased
            if (newQuestions[index].options) {
                newQuestions[index].options = newQuestions[index].options!.map(opt => ({
                    ...opt,
                    score: Math.min(opt.score, newWeight)
                }));
            }
        }

        // Auto-populate Yes/No options if switching to yesno
        if (field === 'inputType' && value === 'yesno' && (!newQuestions[index].options || newQuestions[index].options?.length === 0)) {
            newQuestions[index].options = [
                { text: 'Yes', score: newQuestions[index].weight || 5 },
                { text: 'No', score: 0 }
            ];
        } else if (field === 'inputType' && value === 'select' && (!newQuestions[index].options)) {
            newQuestions[index].options = [];
        }

        newQuestions[index] = { ...newQuestions[index], [field]: value };
        setQuestions(newQuestions);
    };

    const addOption = (questionIndex: number) => {
        const newQuestions = [...questions];
        if (!newQuestions[questionIndex].options) newQuestions[questionIndex].options = [];
        newQuestions[questionIndex].options!.push({ text: '', score: 0 });
        setQuestions(newQuestions);
    };

    const updateOption = (questionIndex: number, optionIndex: number, field: 'text' | 'score', value: any) => {
        const newQuestions = [...questions];
        if (newQuestions[questionIndex].options) {
            let finalValue = value;
            if (field === 'score') {
                const maxWeight = newQuestions[questionIndex].weight || 0;
                finalValue = Math.min(parseFloat(value) || 0, maxWeight);
            }

            newQuestions[questionIndex].options![optionIndex] = {
                ...newQuestions[questionIndex].options![optionIndex],
                [field]: finalValue
            };
            setQuestions(newQuestions);
        }
    };

    const removeOption = (questionIndex: number, optionIndex: number) => {
        const newQuestions = [...questions];
        if (newQuestions[questionIndex].options) {
            newQuestions[questionIndex].options = newQuestions[questionIndex].options!.filter((_, i) => i !== optionIndex);
            setQuestions(newQuestions);
        }
    };

    const handleSave = async () => {
        if (questions.some(q => !q.questionText)) {
            toast.error('All questions must have text');
            return;
        }

        // Validate option scores vs weight
        for (let i = 0; i < questions.length; i++) {
            const q = questions[i];
            if (q.inputType === 'select' || q.inputType === 'yesno') {
                const invalidOption = q.options?.find(opt => opt.score > q.weight);
                if (invalidOption) {
                    toast.error(`Question ${i + 1}: Option "${invalidOption.text}" score (${invalidOption.score}) exceeds question weightage (${q.weight})`);
                    return;
                }
            }
        }

        if (totalWeight !== 100) {
            toast.error(`Total weightage must be exactly 100. Current total: ${totalWeight}`);
            return;
        }

        try {
            setLoading(true);
            await API.createQuestionnaireVersion({
                version,
                questions
            });
            toast.success('Questionnaire version created successfully');
            navigate('/questionnaires'); // Redirect to list after save
        } catch (error) {
            console.error(error);
            toast.error('Failed to create questionnaire');
        } finally {
            setLoading(false);
        }
    };

    if (fetching) {
        return (
            <div className="flex justify-center p-12">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-re-red"></div>
            </div>
        );
    }

    return (
        <div className="p-6 bg-white rounded-lg shadow-md max-w-[1600px] mx-auto">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4 border-b border-gray-100 pb-6">
                <div className="flex items-center gap-3">
                    <button
                        onClick={() => navigate('/questionnaires')}
                        className="p-2 hover:bg-slate-100 rounded-full transition-colors text-slate-500"
                    >
                        <ArrowLeft size={20} />
                    </button>
                    <div>
                        <h2 className="text-2xl font-bold text-slate-900">
                            {id ? 'Edit Questionnaire Version' : 'Create New Version'}
                        </h2>
                        <p className="text-slate-500 text-sm mt-1">
                            {id ? 'Modify existing template and save as new version' : 'Define questions, logic and weightage'}
                        </p>
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-4 w-full md:w-auto">
                    <div className={`flex items-center gap-2 px-3 py-2 rounded-lg border ${totalWeight === 100 ? 'bg-green-50 border-green-200 text-green-700' : 'bg-red-50 border-red-200 text-re-red-hover'}`}>
                        {totalWeight !== 100 && <AlertCircle size={16} />}
                        <span className="text-sm font-semibold">Total Score: {totalWeight}/100</span>
                    </div>

                    <div className="flex items-center gap-2 flex-1 md:flex-initial">
                        <input
                            type="text"
                            value={version}
                            onChange={(e) => setVersion(e.target.value)}
                            className="border border-slate-300 p-2 rounded-lg w-full md:w-48 text-sm focus:ring-2 focus:ring-red-500 outline-none"
                            placeholder="Version Name (e.g. v2.0)"
                        />
                        <button
                            onClick={handleSave}
                            disabled={loading}
                            className="bg-re-red text-white px-6 py-2 rounded-lg flex items-center gap-2 hover:bg-re-red-hover disabled:bg-slate-300 disabled:cursor-not-allowed transition shadow-sm font-medium whitespace-nowrap"
                        >
                            <Save size={18} /> {loading ? 'Saving...' : 'Publish'}
                        </button>
                    </div>
                </div>
            </div>

            <div className="space-y-4">
                {questions.map((q, index) => (
                    <div key={index} className="group border border-slate-200 p-5 rounded-xl bg-slate-50/50 hover:bg-white hover:shadow-md transition-all duration-200 flex gap-4 items-start relative">
                        <div className="pt-2.5">
                            <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center text-slate-600 font-semibold text-sm">
                                {index + 1}
                            </div>
                        </div>

                        <div className="flex-1 flex flex-col gap-4">
                            <div className="grid grid-cols-1 md:grid-cols-12 gap-5">
                                <div className="md:col-span-6 lg:col-span-5">
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Question Text</label>
                                    <input
                                        type="text"
                                        value={q.questionText}
                                        onChange={(e) => updateQuestion(index, 'questionText', e.target.value)}
                                        className="w-full border border-slate-300 p-2.5 rounded-lg focus:ring-2 focus:ring-red-500 outline-none transition-shadow"
                                        placeholder="Enter your question here..."
                                    />
                                </div>

                                <div className="md:col-span-6 lg:col-span-3">
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Section</label>
                                    <select
                                        value={q.sectionName}
                                        onChange={(e) => updateQuestion(index, 'sectionName', e.target.value)}
                                        className="w-full border border-slate-300 p-2.5 rounded-lg focus:ring-2 focus:ring-red-500 outline-none bg-white"
                                    >
                                        {SECTIONS.map(s => <option key={s} value={s}>{s}</option>)}
                                    </select>
                                </div>

                                <div className="md:col-span-4 lg:col-span-2">
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Input Type</label>
                                    <select
                                        value={q.inputType}
                                        onChange={(e) => updateQuestion(index, 'inputType', e.target.value as any)}
                                        className="w-full border border-slate-300 p-2.5 rounded-lg focus:ring-2 focus:ring-red-500 outline-none bg-white"
                                    >
                                        <option value="text">One Liner</option>
                                        <option value="email">Email Address</option>
                                        <option value="textarea">Paragraph</option>
                                        <option value="number">Numeric</option>
                                        <option value="file">File Upload</option>
                                        <option value="yesno">Yes / No</option>
                                        <option value="select">Options (Dropdown)</option>
                                        <option value="radio">Options (Radio)</option>
                                    </select>
                                </div>

                                <div className="md:col-span-4 lg:col-span-2">
                                    <div className="flex items-center gap-3 h-full pt-6">
                                        <div className="flex-1">
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    value={isNaN(q.weight) ? 0 : q.weight}
                                                    onChange={(e) => updateQuestion(index, 'weight', parseFloat(e.target.value) || 0)}
                                                    className="w-full border border-slate-300 p-2.5 rounded-lg focus:ring-2 focus:ring-red-500 outline-none pl-3 pr-8"
                                                    title="Weightage"
                                                />
                                                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs font-bold">%</span>
                                            </div>
                                        </div>

                                        {/* <div className="flex items-center gap-2 px-3 py-2.5 bg-white border border-slate-200 rounded-lg cursor-pointer hover:border-red-300 transition-colors"
                                        onClick={() => updateQuestion(index, 'isMandatory', !q.isMandatory)}
                                    >
                                        <div className={`w-4 h-4 rounded border flex items-center justify-center transition-colors ${q.isMandatory ? 'bg-re-red border-re-red' : 'border-slate-300'}`}>
                                            {q.isMandatory && <div className="w-2 h-2 bg-white rounded-sm" />}
                                        </div>
                                        <span className="text-xs font-medium text-slate-600 select-none">Req.</span>
                                    </div> */}
                                    </div>
                                </div>
                            </div>

                            {/* Options Editor for Select/YesNo */}
                            {(q.inputType === 'select' || q.inputType === 'yesno' || q.inputType === 'radio' || q.inputType === 'mcq') && (
                                <div className="w-full mt-4 pl-4 md:pl-16 border-t border-slate-100 pt-4">
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">
                                        Answer Options & Scores
                                    </label>
                                    <div className="space-y-2">
                                        {q.options?.map((opt, optIndex) => (
                                            <div key={optIndex} className="flex items-center gap-3">
                                                <input
                                                    type="text"
                                                    value={opt.text}
                                                    onChange={(e) => updateOption(index, optIndex, 'text', e.target.value)}
                                                    className="flex-1 border border-slate-300 p-2 rounded-md text-sm focus:ring-1 focus:ring-red-500 outline-none"
                                                    placeholder={`Option ${optIndex + 1}`}
                                                />
                                                <div className="flex items-center gap-2">
                                                    <span className="text-xs text-slate-400 font-medium">Score:</span>
                                                 <input
                                                        type="number"
                                                        value={isNaN(opt.score) ? 0 : opt.score}
                                                        max={isNaN(q.weight) ? 0 : q.weight}
                                                        min={0}
                                                        onChange={(e) => updateOption(index, optIndex, 'score', e.target.value)}
                                                        className={`w-20 border ${(opt.score > q.weight) || isNaN(opt.score) ? 'border-red-500 text-red-600' : 'border-slate-300'} p-2 rounded-md text-sm focus:ring-1 focus:ring-red-500 outline-none`}
                                                    />
                                                </div>
                                                <button
                                                    onClick={() => removeOption(index, optIndex)}
                                                    className="p-1.5 text-slate-400 hover:text-red-500 transition-colors"
                                                    title="Remove Option"
                                                >
                                                    <Trash2 size={16} />
                                                </button>
                                            </div>
                                        ))}
                                    </div>
                                    <button
                                        onClick={() => addOption(index)}
                                        className="mt-3 text-sm flex items-center gap-1 text-re-red hover:text-re-red-hover font-medium"
                                    >
                                        <Plus size={16} /> Add Option
                                    </button>
                                </div>
                            )}
                        </div>

                        <button
                            onClick={() => removeQuestion(index)}
                            className="absolute -right-3 -top-3 md:static md:mt-8 md:mr-2 w-8 h-8 flex items-center justify-center rounded-full bg-white md:bg-transparent text-slate-400 hover:text-red-600 hover:bg-red-50 border border-slate-200 md:border-transparent shadow-sm md:shadow-none transition-all"
                            title="Remove Question"
                        >
                            <Trash2 size={18} />
                        </button>
                    </div>
                ))}
            </div>

            <button
                onClick={addQuestion}
                className="mt-8 w-full border-2 border-dashed border-slate-300 p-4 rounded-xl text-slate-500 hover:border-red-500 hover:text-re-red hover:bg-red-50/30 flex justify-center items-center gap-2 transition-all font-medium"
            >
                <Plus size={20} /> Add Another Question
            </button>
        </div >
    );
};

export default QuestionnaireBuilder;
