import { useState } from "react"; import { useMutation } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { Sparkles, Loader2, PenLine, CheckCircle, BarChart3, ChevronDown } from "lucide-react"; import { coachingService } from "@/services/coaching.service"; import { useToast } from "@/hooks/use-toast"; type Mode = "improve" | "grammar" | "band" | null; interface Props { text: string; task_type?: string; } export default function AiWritingHelper({ text, task_type = "ielts_writing" }: Props) { const [open, setOpen] = useState(false); const [activeMode, setActiveMode] = useState(null); const [showResult, setShowResult] = useState(false); const { toast } = useToast(); const mutation = useMutation({ mutationFn: (mode: NonNullable) => coachingService.writingHelp({ text: text.trim(), task_type: `${task_type}:${mode}`, }), onSuccess: () => setShowResult(true), onError: (err: Error) => { toast({ title: "Writing help failed", description: err.message || "Could not analyze your writing. Try again.", variant: "destructive", }); }, }); const handleAction = (mode: Mode) => { if (!mode) return; if (!text.trim()) { toast({ title: "Add some text first", description: "Enter your draft in the text area so AI can analyze it.", variant: "destructive", }); return; } setActiveMode(mode); setShowResult(false); mutation.mutate(mode); }; const loading = mutation.isPending; return (
{loading && (
AI is analyzing your writing...
)} {showResult && !loading && mutation.data && activeMode === "improve" && (
{mutation.data.feedback && (

Feedback

{mutation.data.feedback}

)} {mutation.data.improved && (

Improved Version

{mutation.data.improved}

)}
)} {showResult && !loading && mutation.data && activeMode === "grammar" && (

Grammar notes

{(mutation.data.grammar_notes?.length ?? 0) > 0 ? ( mutation.data.grammar_notes!.map((note, i) => (

{note}

)) ) : (

No grammar issues flagged.

)} {mutation.data.feedback ? (

{mutation.data.feedback}

) : null}
)} {showResult && !loading && mutation.data && activeMode === "band" && (

Estimated band / assessment

{mutation.data.feedback}

{mutation.data.improved ? (

{mutation.data.improved}

) : null}
)}
); }