"use client";

import { type ReactNode } from "react";
import {
  useAiProviders,
  useUpdateAiProvider,
  useAiUsage,
} from "@/hooks/use-ai-settings";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Button,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
  Badge,
} from "@/components/ui";
import { t } from "@/lib/i18n";

interface StatCardProps {
  label: string;
  value: number | string;
  suffix?: string;
}

function StatCard({ label, value, suffix }: StatCardProps): ReactNode {
  return (
    <PaperCard className="p-4">
      <p
        style={{
          fontSize: 11,
          color: "var(--color-ink-muted)",
          textTransform: "uppercase",
          letterSpacing: "0.05em",
        }}
      >
        {label}
      </p>
      <p
        style={{
          fontFamily: "var(--font-serif)",
          fontSize: 28,
          color: "var(--color-ink)",
          margin: "8px 0 0 0",
        }}
      >
        {value}
        {suffix && (
          <span
            style={{
              fontSize: 14,
              color: "var(--color-ink-muted)",
              marginLeft: 4,
            }}
          >
            {suffix}
          </span>
        )}
      </p>
    </PaperCard>
  );
}

export default function AiSettingsPage(): ReactNode {
  const { data: providers, loading, error, refetch } = useAiProviders();
  const { data: usage } = useAiUsage();
  const [updateProvider, mutationState] = useUpdateAiProvider();
  const { show } = useToast();

  const handleToggle = async (id: string, isActive: boolean) => {
    const res = await updateProvider(id, { isActive: !isActive });
    if (res) {
      show("success", `Provider 已${!isActive ? "启用" : "禁用"}`);
      refetch();
    } else if (mutationState.error) {
      show("error", "操作失败", mutationState.error.message);
    }
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.aiSettings.title")}
        description="AI 服务商与用量管理"
      />

      {/* AI Provider 列表 */}
      <PaperCard className="p-4 mb-6">
        <h3
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 16,
            color: "var(--color-ink)",
            marginBottom: 12,
          }}
        >
          {t("admin.aiSettings.providers")}
        </h3>
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && providers && (
          <>
            {providers.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <Table
                headers={[
                  t("admin.common.name"),
                  "类型",
                  t("admin.aiSettings.model"),
                  t("admin.aiSettings.isPublic"),
                  t("admin.aiSettings.isActive"),
                  "API Base",
                  t("admin.common.createdAt"),
                ]}
              >
                {providers.map((p) => (
                  <TableRow key={p.id}>
                    <TableCell>{p.name}</TableCell>
                    <TableCell>
                      <span
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                        }}
                      >
                        {p.type}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                        }}
                      >
                        {p.model}
                      </span>
                    </TableCell>
                    <TableCell>
                      <Badge status={p.isPublic ? "active" : "disabled"} />
                    </TableCell>
                    <TableCell>
                      <Button
                        variant={p.isActive ? "primary" : "secondary"}
                        onClick={() => handleToggle(p.id, p.isActive)}
                        disabled={mutationState.loading}
                      >
                        {p.isActive ? "启用" : "禁用"}
                      </Button>
                    </TableCell>
                    <TableCell>
                      <span
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                          color: "var(--color-ink-muted)",
                        }}
                      >
                        {p.apiBase}
                      </span>
                    </TableCell>
                    <TableCell style={{ whiteSpace: "nowrap" }}>
                      {new Date(p.createdAt).toLocaleDateString("zh-CN")}
                    </TableCell>
                  </TableRow>
                ))}
              </Table>
            )}
          </>
        )}
      </PaperCard>

      {/* AI 用量统计 */}
      {usage && (
        <>
          <div className="grid grid-cols-3 gap-4 mb-6">
            <StatCard
              label={t("admin.aiSettings.totalRequests")}
              value={usage.totalRequests}
            />
            <StatCard
              label={t("admin.aiSettings.totalTokens")}
              value={usage.totalTokens}
            />
            <StatCard
              label={t("admin.aiSettings.totalCost")}
              value={`$${usage.totalCost.toFixed(2)}`}
            />
          </div>

          {/* Provider 用量明细 */}
          <PaperCard className="p-4 mb-6">
            <h3
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 16,
                color: "var(--color-ink)",
                marginBottom: 12,
              }}
            >
              {t("admin.aiSettings.usage")} - {t("admin.aiSettings.provider")}
            </h3>
            <Table
              headers={[
                t("admin.aiSettings.provider"),
                t("admin.aiSettings.totalRequests"),
                t("admin.aiSettings.totalTokens"),
                t("admin.aiSettings.totalCost"),
              ]}
            >
              {usage.byProvider.map((row) => (
                <TableRow key={row.providerName}>
                  <TableCell>{row.providerName}</TableCell>
                  <TableCell style={{ fontFamily: "var(--font-mono)" }}>
                    {row.requests}
                  </TableCell>
                  <TableCell style={{ fontFamily: "var(--font-mono)" }}>
                    {row.tokens}
                  </TableCell>
                  <TableCell style={{ fontFamily: "var(--font-mono)" }}>
                    ${row.cost.toFixed(2)}
                  </TableCell>
                </TableRow>
              ))}
            </Table>
          </PaperCard>

          {/* 7 天趋势 */}
          <PaperCard className="p-4">
            <h3
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 16,
                color: "var(--color-ink)",
                marginBottom: 12,
              }}
            >
              7 {t("admin.auditLogs.trend")}
            </h3>
            <Table
              headers={[
                "日期",
                t("admin.aiSettings.totalRequests"),
                t("admin.aiSettings.totalTokens"),
              ]}
            >
              {usage.byDay.map((row) => (
                <TableRow key={row.date}>
                  <TableCell style={{ whiteSpace: "nowrap" }}>
                    {row.date}
                  </TableCell>
                  <TableCell style={{ fontFamily: "var(--font-mono)" }}>
                    {row.requests}
                  </TableCell>
                  <TableCell style={{ fontFamily: "var(--font-mono)" }}>
                    {row.tokens}
                  </TableCell>
                </TableRow>
              ))}
            </Table>
          </PaperCard>
        </>
      )}
    </div>
  );
}
