"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 { formatMoney } from "@/lib/utils";
import {
  PageHeader,
  Button,
  Dialog,
  Input,
  DataTable,
  EmptyState,
  LoadingState,
  ErrorState,
  Badge,
  FormField,
  Select,
} from "@/components/ds";

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

export default function ServicesPage() {
  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, "services"],
    queryFn: () => beautyBusinessApi.services.list(tenantId!),
    enabled: !!tenantId,
  });

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

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

  const createM = useMutation({
    mutationFn: (d: z.infer<typeof createSchema>) =>
      beautyBusinessApi.services.create(tenantId!, {
        organization_id: d.organization_id,
        code: d.code,
        name: d.name,
        description: d.description || undefined,
        base_duration_minutes: d.base_duration_minutes
          ? Number(d.base_duration_minutes)
          : undefined,
        base_price: d.base_price ? Number(d.base_price) : 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: "base_duration_minutes", header: "مدت (دقیقه)" },
          {
            key: "base_price",
            header: "قیمت پایه",
            render: (r) =>
              r.base_price != null ? formatMoney(String(r.base_price)) : "—",
          },
          {
            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="سازمان" error={createForm.formState.errors.organization_id?.message}>
            <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("description")} />
          </FormField>
          <FormField label="مدت (دقیقه)">
            <Input type="number" {...createForm.register("base_duration_minutes")} />
          </FormField>
          <FormField label="قیمت پایه">
            <Input type="number" {...createForm.register("base_price")} />
          </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>
  );
}
