"use client";

import { useEffect, useState } from "react";
import { Sparkles, Loader2 } from "lucide-react";
import { aiSummary } from "@/lib/api";

interface Props {
  carId: string;
  carName: string;
}

export default function AISummaryCard({ carId, carName }: Props) {
  const [summary, setSummary] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(false);

    aiSummary(carId)
      .then((res) => {
        if (!cancelled) setSummary(res.summary);
      })
      .catch(() => {
        if (!cancelled) setError(true);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => { cancelled = true; };
  }, [carId]);

  // Don't render if no OpenAI key (API returns 503 which causes error=true)
  if (error || (!loading && !summary)) return null;

  return (
    <div className="rounded-[28px] bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-700 overflow-hidden shadow-[0_8px_30px_rgba(37,99,235,0.25)]">
      <div className="px-6 py-5">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-10 h-10 rounded-2xl bg-white/20 backdrop-blur flex items-center justify-center">
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          <div>
            <p className="text-[10px] uppercase tracking-[0.2em] text-blue-200 font-black">
              DriveHub Insight
            </p>
            <p className="text-base font-black text-white leading-tight">
              Expert Overview
            </p>
          </div>
        </div>

        {loading ? (
          <div className="flex items-center gap-3 py-3">
            <Loader2 className="w-4 h-4 text-blue-200 animate-spin shrink-0" />
            <p className="text-sm text-blue-200">
              Loading overview for {carName}…
            </p>
          </div>
        ) : (
          <p className="text-sm leading-relaxed text-blue-50 font-medium">
            {summary}
          </p>
        )}

        <p className="text-[10px] text-blue-300 mt-4">
          Based on specifications and user feedback
        </p>
      </div>
    </div>
  );
}
