"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Sparkles } from "lucide-react";
import { apiPostPublic, ApiClientError } from "@/lib/api/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

type CoffeeAdvisorPick = {
  name: string;
  reason: string;
  menuItemId?: string | null;
};

type CoffeeAdvisorResult = {
  summary: string;
  picks: CoffeeAdvisorPick[];
};

type CoffeeAdvisorPanelProps = {
  cafeSlug: string;
};

export function CoffeeAdvisorPanel({ cafeSlug }: CoffeeAdvisorPanelProps) {
  const t = useTranslations("discoverPublic.coffeeAdvisor");
  const [purpose, setPurpose] = useState("");
  const [result, setResult] = useState<CoffeeAdvisorResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    const trimmed = purpose.trim();
    if (trimmed.length < 3) return;
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const data = await apiPostPublic<CoffeeAdvisorResult>(
        "/api/public/coffee-advisor",
        { purpose: trimmed, cafeSlug }
      );
      setResult(data);
    } catch (e) {
      if (e instanceof ApiClientError && e.code === "AI_NOT_CONFIGURED") {
        setError(t("notConfigured"));
      } else {
        setError(t("failed"));
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="rounded-xl border border-primary/20 bg-gradient-to-b from-[#E1F5EE]/40 to-card">
      <CardHeader className="pb-2">
        <CardTitle className="flex items-center gap-2 text-base">
          <Sparkles className="h-4 w-4 text-primary" aria-hidden />
          {t("title")}
        </CardTitle>
        <p className="text-xs text-muted-foreground">{t("subtitle")}</p>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="flex flex-col gap-2 sm:flex-row">
          <Input
            value={purpose}
            onChange={(e) => setPurpose(e.target.value)}
            placeholder={t("placeholder")}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !loading) void submit();
            }}
          />
          <Button
            type="button"
            className="shrink-0 bg-primary hover:bg-primary/90"
            disabled={loading || purpose.trim().length < 3}
            onClick={() => void submit()}
          >
            {loading ? t("loading") : t("submit")}
          </Button>
        </div>
        {error ? (
          <p className="text-sm text-destructive">{error}</p>
        ) : null}
        {result ? (
          <div className="space-y-3 rounded-lg border border-primary/15 bg-card/80 p-3">
            <p className="text-sm leading-relaxed">{result.summary}</p>
            {result.picks.length > 0 ? (
              <ul className="space-y-2">
                {result.picks.map((pick) => (
                  <li
                    key={`${pick.name}-${pick.menuItemId ?? "x"}`}
                    className="rounded-lg border border-border/60 bg-background px-3 py-2"
                  >
                    <p className="text-sm font-medium text-primary">{pick.name}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{pick.reason}</p>
                  </li>
                ))}
              </ul>
            ) : null}
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
