"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button, Dialog, FormField, PageHeader, Textarea, EmptyState } from "@/components/ds";
import { loyaltyApi } from "@/modules/loyalty/services/loyalty-api";
import { useTenantId } from "@/hooks/useTenantId";
import { LoyaltyBreadcrumbs } from "@/modules/loyalty/components/LoyaltyBreadcrumbs";
import { LoyaltyPageLoader, LoyaltyPageError } from "@/modules/loyalty/pages/shared";
import { LoyaltyTablePage } from "@/modules/loyalty/design-system";

export default function PointRulesPage() {
  const { tenantId } = useTenantId();
  const qc = useQueryClient();
  const [edit, setEdit] = useState<{ id: string; version: number; settings: string } | null>(null);

  const q = useQuery({
    queryKey: ["loyalty", tenantId, "programs-settings"],
    queryFn: () => loyaltyApi.programs.list(tenantId!, { page: 1, page_size: 500 }),
    enabled: !!tenantId,
  });

  const save = useMutation({
    mutationFn: () =>
      loyaltyApi.programs.update(tenantId!, edit!.id, {
        settings: JSON.parse(edit!.settings || "{}"),
        version: edit!.version,
      }),
    onSuccess: () => {
      toast.success("تنظیمات ذخیره شد");
      setEdit(null);
      qc.invalidateQueries({ queryKey: ["loyalty", tenantId, "programs"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId || q.isLoading) return <LoyaltyPageLoader />;
  if (q.error) return <LoyaltyPageError error={q.error} onRetry={() => q.refetch()} />;

  return (
    <div>
      <LoyaltyBreadcrumbs items={[{ label: "قوانین امتیاز" }]} />
      <PageHeader
        title="قوانین امتیاز"
        description="قوانین کسب/مصرف در program.settings و campaign.rules نگهداری می‌شوند."
      />
      <LoyaltyTablePage
        title="تنظیمات برنامه"
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          {
            key: "settings",
            header: "settings",
            render: (r) => (
              <code className="text-xs">{JSON.stringify(r.settings ?? {}).slice(0, 80)}</code>
            ),
          },
          {
            key: "actions",
            header: "عملیات",
            searchable: false,
            render: (r) => (
              <Button
                size="sm"
                variant="outline"
                onClick={() =>
                  setEdit({
                    id: String(r.id),
                    version: Number(r.version),
                    settings: JSON.stringify(r.settings ?? {}, null, 2),
                  })
                }
              >
                ویرایش JSON
              </Button>
            ),
          },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="برنامه‌ای نیست" />}
      />
      <Dialog open={!!edit} onClose={() => setEdit(null)} title="ویرایش settings">
        <FormField label="JSON">
          <Textarea
            rows={12}
            value={edit?.settings ?? ""}
            onChange={(e) => setEdit((x) => (x ? { ...x, settings: e.target.value } : x))}
          />
        </FormField>
        <Button className="mt-3" loading={save.isPending} onClick={() => save.mutate()}>
          ذخیره
        </Button>
      </Dialog>
    </div>
  );
}
