import { useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Sparkles, RefreshCw, Loader2, Lightbulb } from "lucide-react";
import { coachingService } from "@/services/coaching.service";
import { useToast } from "@/hooks/use-toast";

export default function AiStudyCoach() {
  const { toast } = useToast();

  const suggestMutation = useMutation({
    mutationFn: () => coachingService.suggest(),
    onError: (err: Error) => {
      toast({
        variant: "destructive",
        title: "Could not load coach tips",
        description: err.message || "Try refreshing in a moment.",
      });
    },
  });

  useEffect(() => {
    suggestMutation.mutate();
    // eslint-disable-next-line react-hooks/exhaustive-deps -- load once on mount
  }, []);

  const refresh = () => {
    suggestMutation.mutate();
  };

  const d = suggestMutation.data;
  const suggestions = d ? [d.suggestion, ...(d.focus_areas ?? []).map((a: string) => `Focus area: ${a}`)].filter(Boolean) : [];
  const planTips = d?.daily_plan?.length
    ? d.daily_plan.map((p: { activity: string; duration_min: number; skill: string }) => `${p.activity} (${p.duration_min}min — ${p.skill})`)
    : d?.motivation ? [d.motivation] : [];

  return (
    <Card className="border-0 shadow-sm bg-primary/5">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base font-semibold flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            Your AI Study Coach
          </CardTitle>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            onClick={refresh}
            disabled={suggestMutation.isPending}
          >
            <RefreshCw className={`h-4 w-4 ${suggestMutation.isPending ? "animate-spin" : ""}`} />
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {suggestMutation.isPending && !suggestMutation.data ? (
          <div className="flex items-center gap-2 text-sm text-muted-foreground py-4 justify-center">
            <Loader2 className="h-5 w-5 animate-spin text-primary" /> Analyzing your performance...
          </div>
        ) : (
          <>
            {suggestions.length > 0 && (
              <div className="mb-4">
                <p className="text-xs font-semibold text-primary mb-2 flex items-center gap-1">
                  <Lightbulb className="h-3.5 w-3.5" /> Suggestions
                </p>
                <ul className="text-sm text-muted-foreground space-y-2 list-disc list-inside">
                  {suggestions.map((s, i) => (
                    <li key={i}>{s}</li>
                  ))}
                </ul>
              </div>
            )}
            {planTips.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-primary mb-2 flex items-center gap-1">
                  <Sparkles className="h-3.5 w-3.5" /> Study plan tips
                </p>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                  {planTips.map((tip, i) => (
                    <div
                      key={i}
                      className="rounded-lg border bg-card p-3 hover:shadow-sm transition-shadow"
                    >
                      <p className="text-sm">{tip}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}
            {!suggestMutation.isPending &&
              suggestions.length === 0 &&
              planTips.length === 0 && (
                <p className="text-sm text-muted-foreground text-center py-4">
                  No suggestions yet. Try refreshing.
                </p>
              )}
          </>
        )}
      </CardContent>
    </Card>
  );
}
