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({ task: task_type, draft: text.trim(), help_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.tips?.length > 0 && (

Feedback

{mutation.data.tips.join(" ")}

)} {mutation.data.improved_text && (

Improved Version

{mutation.data.improved_text}

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

Grammar notes

{(mutation.data.changes?.length ?? 0) > 0 ? ( mutation.data.changes.map((c, i) => (

{c.original} → {c.revised} — {c.reason}

)) ) : (

No grammar issues flagged.

)} {mutation.data.tips?.length > 0 ? (

{mutation.data.tips.join("; ")}

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

Estimated band / assessment

{mutation.data.tips?.join(" ") ?? ""}

{mutation.data.improved_text ? (

{mutation.data.improved_text}

) : null}
)}
); }