"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Plus } from "lucide-react";
import { beautyBusinessApi } from "@/modules/beauty/services/beauty-business-api";
import { useTenantId } from "@/hooks/useTenantId";
import {
  PageHeader,
  Button,
  Dialog,
  Input,
  DataTable,
  EmptyState,
  LoadingState,
  ErrorState,
  Badge,
  FormField,
  Select,
} from "@/components/ds";

const createSchema = z.object({
  organization_id: z.string().optional(),
  code: z.string().min(1, "کد الزامی است"),
  name: z.string().min(1, "نام الزامی است"),
  channel: z.string().optional(),
});

export default function MarketingCampaignsPage() {
  const { tenantId } = useTenantId();
  const qc = useQueryClient();
  const [createOpen, setCreateOpen] = useState(false);

  const orgsQ = useQuery({
    queryKey: ["beauty", tenantId, "organizations"],
    queryFn: () => beautyBusinessApi.organizations.list(tenantId!),
    enabled: !!tenantId,
  });

  const listQ = useQuery({
    queryKey: ["beauty", tenantId, "marketing-campaigns"],
    queryFn: () => beautyBusinessApi.marketingCampaigns.list(tenantId!),
    enabled: !!tenantId,
  });

  const createForm = useForm<z.infer<typeof createSchema>>({
    resolver: zodResolver(createSchema),
    defaultValues: { organization_id: "", code: "", name: "", channel: "" },
  });

  const invalidate = () =>
    qc.invalidateQueries({ queryKey: ["beauty", tenantId, "marketing-campaigns"] });

  const createM = useMutation({
    mutationFn: (d: z.infer<typeof createSchema>) =>
      beautyBusinessApi.marketingCampaigns.create(tenantId!, {
        organization_id: d.organization_id || undefined,
        code: d.code,
        name: d.name,
        channel: d.channel || undefined,
      }),
    onSuccess: async () => {
      toast.success("کمپین ایجاد شد");
      setCreateOpen(false);
      createForm.reset();
      await invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId || listQ.isLoading) return <LoadingState />;
  if (listQ.error) {
    return <ErrorState message={listQ.error.message} onRetry={() => listQ.refetch()} />;
  }

  return (
    <div>
      <PageHeader
        title="کمپین‌های بازاریابی"
        description="مدیریت کمپین‌ها و کانال‌های ارتباطی."
        actions={
          <Button onClick={() => setCreateOpen(true)}>
            <Plus className="h-4 w-4" />
            کمپین جدید
          </Button>
        }
      />

      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "channel", header: "کانال" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge>{String(r.status)}</Badge>,
          },
        ]}
        rows={(listQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState action={<Button onClick={() => setCreateOpen(true)}>ایجاد کمپین</Button>} />}
      />

      <Dialog open={createOpen} onClose={() => setCreateOpen(false)} title="کمپین جدید">
        <form className="space-y-3" onSubmit={createForm.handleSubmit((d) => createM.mutate(d))}>
          <FormField label="سازمان (اختیاری)">
            <Select {...createForm.register("organization_id")}>
              <option value="">—</option>
              {(orgsQ.data ?? []).map((o) => (
                <option key={o.id} value={o.id}>
                  {o.name}
                </option>
              ))}
            </Select>
          </FormField>
          <FormField label="کد" error={createForm.formState.errors.code?.message}>
            <Input {...createForm.register("code")} />
          </FormField>
          <FormField label="نام" error={createForm.formState.errors.name?.message}>
            <Input {...createForm.register("name")} />
          </FormField>
          <FormField label="کانال">
            <Input {...createForm.register("channel")} placeholder="sms, email, push" />
          </FormField>
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>
              انصراف
            </Button>
            <Button type="submit" disabled={createM.isPending}>
              ذخیره
            </Button>
          </div>
        </form>
      </Dialog>
    </div>
  );
}
