'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useForm } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { MessageSquareTextIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import Confetti from 'react-confetti';
import { useWindowSize } from 'react-use';
import { toast } from 'sonner';

export default function Kuisioner({ questions, success }) {
    const { width, height } = useWindowSize();
    const [showModal, setShowModal] = useState(false);
    const { data, setData, post, processing, errors, reset } = useForm({
        phone_number: '',
        answers: [],
    });

    const handleAnswerChange = (id, value) => {
        const updatedAnswers = [...data.answers];
        const existingIndex = updatedAnswers.findIndex((item) => item.question_id === id);

        if (existingIndex !== -1) {
            updatedAnswers[existingIndex].answer = value;
        } else {
            updatedAnswers.push({ question_id: id, answer: value });
        }

        setData('answers', updatedAnswers);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        if (data.answers.length < questions.length) {
            toast.error('Harap isi semua pertanyaan sebelum submit.');
            return;
        }
        post('/kuisioner');
    };

    useEffect(() => {
        if (success) {
            setShowModal(true);
            toast.success(success);
            reset();
        }
    }, [success]);

    useEffect(() => {
        if (showModal) {
            const timer = setTimeout(() => setShowModal(false), 5000);
            return () => clearTimeout(timer);
        }
    }, [showModal]);

    return (
        <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-indigo-100 to-blue-50 p-4">
            {showModal && <Confetti width={width} height={height} numberOfPieces={200} />}
            <motion.div initial={{ opacity: 0, y: 30 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8 }} className="w-full max-w-lg">
                <Card className="rounded-3xl border-none bg-white/90 shadow-xl backdrop-blur-md">
                    <CardHeader className="space-y-4 text-center">
                        <img src="/images/logo_rs.jpeg" alt="Logo RS" className="mx-auto h-28 w-28 object-contain" />
                        <CardTitle className="text-3xl font-extrabold text-blue-900">🩺 Kuisioner Pelayanan RS</CardTitle>
                        <CardDescription className="text-lg text-gray-500">
                            Kami ingin mendengar pendapat Anda. Jawaban Anda sangat berarti bagi kami dalam meningkatkan kualitas pelayanan.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6 px-6 py-6">
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="space-y-2">
                                <Label htmlFor="phone_number" className="text-lg font-medium text-gray-700">
                                    Nomor WhatsApp
                                </Label>
                                <Input
                                    id="phone_number"
                                    value={data.phone_number}
                                    onChange={(e) => setData('phone_number', e.target.value)}
                                    placeholder="Contoh: 08xxxxxxxxxx"
                                    className={`w-full rounded-md p-3 text-base transition duration-300 ease-in-out ${errors.phone_number ? 'border-red-500 ring-2 ring-red-400' : 'focus:border-blue-500 focus:ring-2 focus:ring-blue-500'}`}
                                    required
                                />
                                {errors.phone_number && <p className="mt-1 text-sm text-red-500">{errors.phone_number}</p>}
                            </div>

                            {questions.map((q) => (
                                <div key={q.id} className="space-y-2">
                                    <Label htmlFor={`q-${q.id}`} className="flex items-center gap-2 text-lg font-medium text-gray-700">
                                        <MessageSquareTextIcon className="h-5 w-5 text-blue-600" />
                                        {q.question_text}
                                    </Label>
                                    <Input
                                        id={`q-${q.id}`}
                                        type="text"
                                        placeholder="Ketik jawaban Anda di sini"
                                        value={data.answers.find((answer) => answer.question_id === q.id)?.answer || ''}
                                        onChange={(e) => handleAnswerChange(q.id, e.target.value)}
                                        className={`w-full rounded-md p-3 transition-all ease-in-out focus:border-blue-500 focus:ring-2 focus:ring-blue-500 ${errors.answers ? 'border-red-500 ring-2 ring-red-400' : ''}`}
                                        required
                                    />
                                </div>
                            ))}

                            {errors.answers && <p className="mt-1 text-sm text-red-500">{errors.answers}</p>}

                            <Button
                                type="submit"
                                disabled={processing}
                                className="w-full rounded-md bg-blue-600 py-3 text-base font-semibold text-white transition-all ease-in-out hover:bg-blue-700"
                            >
                                {processing ? (
                                    <div className="flex items-center justify-center">
                                        <div className="h-5 w-5 animate-spin rounded-full border-4 border-t-4 border-white"></div>
                                    </div>
                                ) : (
                                    'Kirim Jawaban'
                                )}
                            </Button>
                        </form>
                    </CardContent>
                </Card>
            </motion.div>

            {/* Modal */}
            {showModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
                    <motion.div
                        initial={{ scale: 0.8, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        transition={{ duration: 0.3 }}
                        className="rounded-xl bg-white p-6 text-center shadow-xl"
                    >
                        <h2 className="mb-4 text-2xl font-bold text-green-600">🎉 Terima Kasih!</h2>
                        <p className="text-gray-700">Jawaban Anda telah berhasil dikirim.</p>
                        <Button className="mt-6 bg-green-600 hover:bg-green-700" onClick={() => setShowModal(false)}>
                            Tutup
                        </Button>
                    </motion.div>
                </div>
            )}
        </div>
    );
}
