"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  Button,
  Dialog,
  FormField,
  Input,
  Select,
  Textarea,
  PageHeader,
  EmptyState,
} from "@/components/ds";
import { crmApi } from "@/modules/crm/services/crm-api";
import { useTenantId } from "@/hooks/useTenantId";
import { CrmPageLoader, CrmPageError } from "@/modules/crm/pages/shared";
import { CrmBreadcrumbs } from "@/modules/crm/components/CrmBreadcrumbs";

export default function NotesPage() {
  const { tenantId } = useTenantId();
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [entityType, setEntityType] = useState("lead");
  const [entityId, setEntityId] = useState("");

  const notesQ = useQuery({
    queryKey: ["crm", tenantId, "notes", entityType, entityId],
    queryFn: () => crmApi.notes.list(tenantId!, entityType, entityId),
    enabled: !!tenantId && !!entityId,
  });

  const form = useForm({ defaultValues: { body: "" } });

  const createM = useMutation({
    mutationFn: (body: string) =>
      crmApi.notes.create(tenantId!, { entity_type: entityType, entity_id: entityId, body }),
    onSuccess: async () => {
      toast.success("یادداشت ثبت شد");
      setOpen(false);
      form.reset();
      await qc.invalidateQueries({ queryKey: ["crm", tenantId, "notes"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId) return <CrmPageLoader />;

  return (
    <div>
      <CrmBreadcrumbs items={[{ label: "یادداشت‌ها" }]} />
      <PageHeader
        title="یادداشت‌ها"
        description="یادداشت نسخه‌دار روی lead/contact/organization."
        actions={
          <Button onClick={() => setOpen(true)} disabled={!entityId}>
            یادداشت جدید
          </Button>
        }
      />
      <div className="mb-4 flex flex-wrap gap-3">
        <Select value={entityType} onChange={(e) => setEntityType(e.target.value)}>
          <option value="lead">سرنخ</option>
          <option value="contact">مخاطب</option>
          <option value="organization">سازمان</option>
        </Select>
        <Input
          placeholder="UUID موجودیت"
          value={entityId}
          onChange={(e) => setEntityId(e.target.value)}
          className="max-w-md"
        />
      </div>
      {entityId && notesQ.isLoading ? <CrmPageLoader /> : null}
      {notesQ.error ? <CrmPageError error={notesQ.error} onRetry={() => notesQ.refetch()} /> : null}
      {entityId && notesQ.data ? (
        <div className="space-y-2">
          {notesQ.data.map((n) => (
            <div
              key={n.id}
              className="rounded-xl border border-[var(--border)] bg-[var(--surface)] p-4"
            >
              <p className="text-sm whitespace-pre-wrap">{n.body}</p>
              <p className="mt-2 text-xs text-[var(--muted)]">v{n.version}</p>
            </div>
          ))}
          {notesQ.data.length === 0 ? <EmptyState title="یادداشتی نیست" /> : null}
        </div>
      ) : (
        !entityId && <EmptyState title="شناسه موجودیت را وارد کنید" />
      )}
      <Dialog open={open} onClose={() => setOpen(false)} title="یادداشت جدید">
        <form className="space-y-3" onSubmit={form.handleSubmit((d) => createM.mutate(d.body))}>
          <FormField label="متن">
            <Textarea {...form.register("body")} rows={5} />
          </FormField>
          <Button type="submit" disabled={createM.isPending}>
            ذخیره
          </Button>
        </form>
      </Dialog>
    </div>
  );
}
