import { useState } from 'react';

import { router } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/Components/ui/dialog';
import { LoadingButton } from '@/Components/ui/loading-button';
import { Textarea } from '@/Components/ui/textarea';

interface NpsPrompt {
    type: string;
    day: number;
}

interface NpsModalProps {
    nps_prompt: NpsPrompt | false;
}

export default function NpsModal({ nps_prompt }: NpsModalProps) {
    const [open, setOpen] = useState<boolean>(!!nps_prompt);
    const [score, setScore] = useState<number | null>(null);
    const [reason, setReason] = useState('');
    const [submitting, setSubmitting] = useState(false);

    if (!nps_prompt) {
        return null;
    }

    const handleSubmit = () => {
        if (score === null) return;

        setSubmitting(true);

        router.post(
            route('nps.store'),
            { score, reason, survey_type: nps_prompt.type },
            {
                onFinish: () => {
                    setSubmitting(false);
                    setOpen(false);
                },
            },
        );
    };

    const handleDismiss = () => {
        setOpen(false);
        router.post(route('nps.dismiss'), {}, { preserveState: true, preserveScroll: true });
    };

    const getScoreLabel = (s: number): string => {
        if (s >= 9) return 'Promoter';
        if (s >= 7) return 'Passive';
        return 'Detractor';
    };

    const getScoreDescription = (s: number): string => {
        if (s <= 2) return 'Very unlikely';
        if (s <= 4) return 'Unlikely';
        if (s <= 6) return 'Neutral';
        if (s <= 8) return 'Likely';
        return 'Very likely';
    };

    const getScoreColor = (s: number): string => {
        if (s >= 9) return 'bg-success text-success-foreground';
        if (s >= 7) return 'bg-warning text-warning-foreground';
        return 'bg-destructive text-destructive-foreground';
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="sm:max-w-md">
                <DialogHeader>
                    <DialogTitle>How likely are you to recommend RankWiz?</DialogTitle>
                    <DialogDescription>
                        On a scale of 0–10, how likely are you to recommend RankWiz to a colleague?
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-4 py-2">
                    {/* Score selector */}
                    <div>
                        <div className="mb-2 flex justify-between text-xs text-muted-foreground">
                            <span>Not at all likely</span>
                            <span>Extremely likely</span>
                        </div>
                        <div className="flex gap-1" role="group" aria-label="Score from 0 to 10">
                            {Array.from({ length: 11 }, (_, i) => (
                                <button
                                    key={i}
                                    type="button"
                                    onClick={() => !submitting && setScore(i)}
                                    disabled={submitting}
                                    aria-label={`Score ${i} out of 10 — ${getScoreDescription(i)}`}
                                    aria-pressed={score === i}
                                    className={`flex h-8 flex-1 items-center justify-center rounded text-sm font-medium transition-colors disabled:opacity-50 ${
                                        score === i
                                            ? getScoreColor(i)
                                            : 'bg-muted text-muted-foreground hover:bg-muted/80'
                                    }`}
                                >
                                    {i}
                                </button>
                            ))}
                        </div>
                        {score !== null && (
                            <p className="mt-1 text-center text-xs text-muted-foreground">{getScoreLabel(score)}</p>
                        )}
                    </div>

                    {/* Optional reason */}
                    <div>
                        <label htmlFor="nps-reason" className="mb-1 block text-sm font-medium text-foreground">
                            What's the main reason for your score? <span className="text-muted-foreground">(optional)</span>
                        </label>
                        <Textarea
                            id="nps-reason"
                            placeholder="Tell us what you think…"
                            value={reason}
                            onChange={(e) => setReason(e.target.value)}
                            rows={3}
                            maxLength={1000}
                        />
                    </div>
                </div>

                <DialogFooter className="gap-2 sm:gap-0">
                    <Button variant="ghost" onClick={handleDismiss} disabled={submitting}>
                        Skip
                    </Button>
                    <LoadingButton onClick={handleSubmit} loading={submitting} loadingText="Submitting…" disabled={score === null}>
                        Submit
                    </LoadingButton>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
