"use client";

import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet, apiPut } from "@/lib/api/client";
import { adminGet, adminPut } from "@/lib/api/admin-client";
import {
  EMPTY_DISCOVER_PROFILE,
  type CafeDiscoverProfile,
} from "@/lib/cafe-discover-profile";
import { CafeDiscoverProfileEditor } from "@/components/discover/cafe-discover-profile-editor";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { notify } from "@/lib/notify";

type ApiDiscoverProfile = {
  themes: string[];
  size?: string | null;
  floors?: string | null;
  vibes: string[];
  occasions: string[];
  spaceFeatures: string[];
  noiseLevel?: string | null;
  priceTier?: string | null;
};

function fromApi(d: ApiDiscoverProfile): CafeDiscoverProfile {
  return {
    themes: d.themes ?? [],
    size: d.size ?? null,
    floors: d.floors ?? null,
    vibes: d.vibes ?? [],
    occasions: d.occasions ?? [],
    spaceFeatures: d.spaceFeatures ?? [],
    noiseLevel: d.noiseLevel ?? null,
    priceTier: d.priceTier ?? null,
  };
}

function toApiBody(p: CafeDiscoverProfile) {
  return {
    themes: p.themes,
    size: p.size,
    floors: p.floors,
    vibes: p.vibes,
    occasions: p.occasions,
    spaceFeatures: p.spaceFeatures,
    noiseLevel: p.noiseLevel,
    priceTier: p.priceTier,
  };
}

type CafeDiscoverProfilePanelProps = {
  cafeId: string;
  mode: "merchant" | "admin";
  compact?: boolean;
};

export function CafeDiscoverProfilePanel({
  cafeId,
  mode,
  compact,
}: CafeDiscoverProfilePanelProps) {
  const t = useTranslations(
    mode === "admin" ? "admin.cafes.discoverProfile" : "settings.discoverProfile"
  );
  const qc = useQueryClient();
  const [profile, setProfile] = useState<CafeDiscoverProfile>(EMPTY_DISCOVER_PROFILE);

  const queryKey =
    mode === "admin"
      ? ["admin", "cafe-discover-profile", cafeId]
      : ["cafe-discover-profile", cafeId];

  const { data, isLoading } = useQuery({
    queryKey,
    queryFn: async () => {
      if (mode === "admin") {
        const res = await adminGet<ApiDiscoverProfile & { cafeId: string; cafeName: string }>(
          `/api/admin/cafes/${cafeId}/discover-profile`
        );
        return fromApi(res);
      }
      const res = await apiGet<ApiDiscoverProfile>(`/api/cafes/${cafeId}/discover-profile`);
      return fromApi(res);
    },
    enabled: !!cafeId,
  });

  useEffect(() => {
    if (data) setProfile(data);
  }, [data]);

  const save = useMutation({
    mutationFn: () => {
      const body = toApiBody(profile);
      return mode === "admin"
        ? adminPut(`/api/admin/cafes/${cafeId}/discover-profile`, body)
        : apiPut(`/api/cafes/${cafeId}/discover-profile`, body);
    },
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey });
      notify.success(t("saved"));
    },
  });

  const content = (
    <>
      {!compact ? (
        <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
      ) : null}
      {isLoading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : (
        <CafeDiscoverProfileEditor
          value={profile}
          onChange={setProfile}
          disabled={save.isPending}
        />
      )}
      <Button
        className="bg-[#0F6E56] hover:bg-[#0c5a46]"
        disabled={save.isPending || isLoading}
        onClick={() => save.mutate()}
      >
        {t("save")}
      </Button>
    </>
  );

  if (compact) {
    return <div className="space-y-4">{content}</div>;
  }

  return (
    <Card className="rounded-xl border border-border/80 shadow-sm">
      <CardHeader className="pb-2">
        <CardTitle className="text-base">{t("title")}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">{content}</CardContent>
    </Card>
  );
}
