"use client";

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

/** Email metadata only — no delivery engine in CRM 6.3 */
export default function EmailsPage() {
  const { tenantId } = useTenantId();
  const [open, setOpen] = useState(false);
  const form = useForm({
    defaultValues: {
      subject: "",
      thread_key: "",
      body_text: "",
      from_address: "",
      to_addresses: "",
    },
  });

  const threadM = useMutation({
    mutationFn: async (d: Record<string, string>) => {
      const thread = await crmApi.emails.createThread(tenantId!, {
        subject: d.subject,
        thread_key: d.thread_key || d.subject,
      });
      await crmApi.emails.createMessage(tenantId!, {
        thread_id: thread.id,
        subject: d.subject,
        body_text: d.body_text,
        from_address: d.from_address,
        to_addresses: d.to_addresses.split(",").map((s) => s.trim()),
      });
    },
    onSuccess: () => {
      toast.success("رشته ایمیل ثبت شد (metadata)");
      setOpen(false);
      form.reset();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId) return null;

  return (
    <div>
      <CrmBreadcrumbs items={[{ label: "ایمیل‌ها" }]} />
      <PageHeader
        title="ایمیل‌ها"
        description="ثبت metadata ایمیل — CRM مالک delivery نیست."
        actions={<Button onClick={() => setOpen(true)}>ثبت ایمیل</Button>}
      />
      <CrmScopeNotice
        title="فقط metadata"
        description="CRM Phase 6.3 فقط thread/message metadata ذخیره می‌کند. ارسال واقعی از Communication Platform انجام می‌شود."
        alternatives={[{ label: "Communication Platform", href: "/dashboard" }]}
      />
      <Dialog open={open} onClose={() => setOpen(false)} title="ثبت metadata ایمیل">
        <form className="space-y-3" onSubmit={form.handleSubmit((d) => threadM.mutate(d))}>
          <FormField label="موضوع">
            <Input {...form.register("subject")} />
          </FormField>
          <FormField label="از">
            <Input {...form.register("from_address")} />
          </FormField>
          <FormField label="به (comma-separated)">
            <Input {...form.register("to_addresses")} />
          </FormField>
          <FormField label="متن">
            <Textarea {...form.register("body_text")} rows={4} />
          </FormField>
          <Button type="submit" disabled={threadM.isPending}>
            ذخیره
          </Button>
        </form>
      </Dialog>
    </div>
  );
}
