"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import type { CustomerGroup, SmsCampaignResult, SmsUsage } from "@/lib/api/types";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

const GROUPS: (CustomerGroup | "all")[] = ["all", "Regular", "Vip", "New", "Employee"];

export function SmsScreen() {
  const t = useTranslations("sms");
  const tCrm = useTranslations("crm");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const queryClient = useQueryClient();

  const [message, setMessage] = useState("");
  const [target, setTarget] = useState<CustomerGroup | "all">("all");
  const [result, setResult] = useState<SmsCampaignResult | null>(null);

  const { data: usage } = useQuery({
    queryKey: ["sms-usage", cafeId],
    queryFn: () => apiGet<SmsUsage>(`/api/cafes/${cafeId}/sms/usage`),
    enabled: !!cafeId,
  });

  const sendCampaign = useMutation({
    mutationFn: () =>
      apiPost<SmsCampaignResult>(`/api/cafes/${cafeId}/sms/campaign`, {
        message,
        targetGroup: target === "all" ? null : target,
      }),
    onSuccess: (data) => {
      setResult(data);
      setMessage("");
      queryClient.invalidateQueries({ queryKey: ["sms-usage", cafeId] });
    },
  });

  if (!cafeId) return null;

  const usageLabel =
    usage?.monthlyLimit === -1
      ? t("unlimited")
      : `${formatNumber(usage?.usedThisMonth ?? 0)} / ${formatNumber(usage?.monthlyLimit ?? 0)}`;

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold">{t("title")}</h2>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("usage")}</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-2xl font-semibold text-primary">{usageLabel}</p>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="space-y-4 pt-6">
          <LabeledField label={t("targetGroup")} htmlFor="sms-target">
            <select
              id="sms-target"
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              value={target}
              onChange={(e) => setTarget(e.target.value as CustomerGroup | "all")}
            >
              {GROUPS.map((g) => (
                <option key={g} value={g}>
                  {g === "all" ? t("allCustomers") : tCrm(`groups.${g}`)}
                </option>
              ))}
            </select>
          </LabeledField>
          <LabeledField label={t("message")} htmlFor="sms-message">
            <textarea
              id="sms-message"
              className="min-h-[120px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />
          </LabeledField>
          <Button
            className="w-full"
            disabled={!message.trim() || sendCampaign.isPending}
            onClick={() => sendCampaign.mutate()}
          >
            {t("send")}
          </Button>
          {result && (
            <p className="text-center text-sm text-muted-foreground">
              {t("sent")}: {formatNumber(result.sentCount)} — {t("failed")}:{" "}
              {formatNumber(result.failedCount)}
            </p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
