'use client';

import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { Star } from 'lucide-react';
import { useState } from 'react';

interface SurveyFormProps {
    patientId: string;
    onSuccess?: () => void;
    onCancel?: () => void;
}

export default function SurveyForm({ patientId, onSuccess, onCancel }: SurveyFormProps) {
    const { t } = useLanguage();
    const [rating, setRating] = useState(0);
    const [feedback, setFeedback] = useState('');
    const [loading, setLoading] = useState(false);
    const [hoverRating, setHoverRating] = useState(0);

    const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (rating === 0) return;

        setLoading(true);
        try {
            const response = await fetch(`${API_BASE_URL}/api/surveys`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ patientId, rating, feedback }),
            });

            if (response.ok) {
                onSuccess?.();
            } else {
                console.error('Failed to submit survey');
            }
        } catch (error) {
            console.error('Error submitting survey:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="py-4">
            <form onSubmit={handleSubmit} className="space-y-6">
                <div className="space-y-2">
                    <label className="block text-sm font-medium text-foreground/80">
                        {t('survey.rating')}
                    </label>
                    <div className="flex gap-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                            <button
                                key={star}
                                type="button"
                                className="focus:outline-none transition-colors p-1 rounded-md hover:bg-accent"
                                onMouseEnter={() => setHoverRating(star)}
                                onMouseLeave={() => setHoverRating(0)}
                                onClick={() => setRating(star)}
                            >
                                <Star
                                    className={`h-8 w-8 ${star <= (hoverRating || rating)
                                        ? 'fill-yellow-400 text-yellow-400'
                                        : 'text-gray-300'
                                        }`}
                                />
                            </button>
                        ))}
                    </div>
                    <p className="text-xs text-muted-foreground">
                        {rating > 0 ? t('survey.starsSelected').replace('{rating}', String(rating)) : t('survey.selectRating')}
                    </p>
                </div>

                <div className="space-y-2">
                    <label htmlFor="feedback" className="block text-sm font-medium text-foreground/80">
                        {t('survey.feedbackLabel')}
                    </label>
                    <Textarea
                        id="feedback"
                        value={feedback}
                        onChange={(e) => setFeedback(e.target.value)}
                        placeholder={t('survey.feedbackPlaceholder')}
                        className="min-h-[100px] rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all resize-y"
                    />
                </div>

                <div className="flex justify-end gap-3 pt-4 border-t">
                    {onCancel && (
                        <Button type="button" variant="outline" onClick={onCancel} className="h-11 px-6 rounded-lg hover:bg-gray-100">
                            {t('common.cancel')}
                        </Button>
                    )}
                    <Button
                        type="submit"
                        disabled={loading || rating === 0}
                        className="h-11 px-6 rounded-lg font-semibold shadow-md active:scale-95 transition-all bg-emerald-600 hover:bg-emerald-700 text-white"
                    >
                        {loading ? t('survey.submitting') : t('survey.submitSurvey')}
                    </Button>
                </div>
            </form>
        </div>
    );
}
