import { Alert } from "react-native";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { t } from "@/lib/i18n";
import {
  Body,
  Button,
  Card,
  EmptyState,
  ErrorView,
  Heading,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
} from "@/components/ui";

/** "Vad plattformen vet om mig" (spec §32): transparens, korrigering, paus, radering. */

interface MemoryOverview {
  sections: Array<{
    kind: string;
    title: string;
    titleSv: string;
    items: Array<{
      id: string;
      summary: string;
      summarySv: string;
      origin: "user_stated" | "observed" | "ai_inferred";
      confidence: number;
      verifiedByUser: boolean;
      paused: boolean;
    }>;
  }>;
  totalCount: number;
  pausedCount: number;
}

export default function MemoryScreen() {
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["memory"],
    queryFn: () => api<MemoryOverview>("/v1/me/memory"),
  });

  const invalidate = () => void queryClient.invalidateQueries({ queryKey: ["memory"] });

  const verify = useMutation({
    mutationFn: (id: string) =>
      api(`/v1/me/memory/${id}`, { method: "PATCH", body: { verified: true } }),
    onSuccess: invalidate,
  });
  const pause = useMutation({
    mutationFn: ({ id, paused }: { id: string; paused: boolean }) =>
      api(`/v1/me/memory/${id}`, { method: "PATCH", body: { paused } }),
    onSuccess: invalidate,
  });
  const remove = useMutation({
    mutationFn: (id: string) => api(`/v1/me/memory/${id}`, { method: "DELETE" }),
    onSuccess: invalidate,
  });
  const removeAll = useMutation({
    mutationFn: () => api("/v1/me/memory", { method: "DELETE" }),
    onSuccess: invalidate,
  });

  if (query.isLoading) return <LoadingView />;
  if (query.isError || !query.data) return <ErrorView onRetry={() => void query.refetch()} />;
  const overview = query.data;

  return (
    <Screen>
      <Small>{t("memory.subtitle")}</Small>
      {overview.totalCount === 0 && <EmptyState text={t("memory.empty")} />}

      {overview.sections.map((section) => (
        <Card key={section.kind}>
          <Heading>{section.title}</Heading>
          {section.items.map((item) => (
            <Card key={item.id} style={item.paused ? { opacity: 0.5 } : undefined}>
              <Body>{item.summary}</Body>
              <Row>
                <Tag
                  label={t(`memory.origin.${item.origin}` as never)}
                  tone={
                    item.origin === "user_stated"
                      ? "success"
                      : item.origin === "observed"
                        ? "neutral"
                        : "warning"
                  }
                />
                {item.verifiedByUser && <Tag label={`✓ ${t("memory.verified")}`} tone="success" />}
                {item.paused && <Tag label={t("memory.paused")} tone="warning" />}
              </Row>
              <Row>
                {!item.verifiedByUser && (
                  <Button
                    label={t("memory.verify")}
                    variant="ghost"
                    onPress={() => verify.mutate(item.id)}
                  />
                )}
                <Button
                  label={item.paused ? t("memory.resume") : t("memory.pause")}
                  variant="ghost"
                  onPress={() => pause.mutate({ id: item.id, paused: !item.paused })}
                />
                <Button
                  label={t("memory.delete")}
                  variant="danger"
                  onPress={() => remove.mutate(item.id)}
                />
              </Row>
            </Card>
          ))}
        </Card>
      ))}

      {overview.totalCount > 0 && (
        <>
          <Spacer />
          <Button
            label={t("memory.deleteAll")}
            variant="danger"
            onPress={() =>
              Alert.alert(t("memory.deleteAllTitle"), t("memory.irreversible"), [
                { text: t("common.cancel"), style: "cancel" },
                {
                  text: t("memory.delete"),
                  style: "destructive",
                  onPress: () => removeAll.mutate(),
                },
              ])
            }
          />
        </>
      )}
      <Small>Personligt minne används aldrig som träningsdata utan separat samtycke.</Small>
    </Screen>
  );
}
