"use client";

import Link from "next/link";
import { useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  FormErrors,
  scrollToFirstError,
  useAppForm,
} from "@/components/ui/tanstack-form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { canTransitionContent } from "@/features/content-approval/lib/workflow";
import {
  createAnnouncementMutation,
  updateAnnouncementMutation,
  updateAnnouncementStateMutation,
} from "../api/mutations";
import type { Announcement } from "../api/types";
import {
  canViewAnnouncementReviewNote,
  hasAnnouncementWorkflowData,
} from "../lib/workflow-visibility";
import {
  announcementDraftSchema,
  type AnnouncementDraftAction,
  type AnnouncementFormValues,
} from "../schemas/announcement";

const attachmentAccept = ".pdf,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx";

export default function AnnouncementForm({
  initialData,
  currentUserId,
  permissions,
}: {
  initialData: Announcement | null;
  currentUserId: string;
  permissions: readonly string[];
}) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const isEdit = Boolean(initialData);
  const [attachment, setAttachment] = useState<File | null>(null);
  const [removeAttachment, setRemoveAttachment] = useState(false);
  const [submitAction, setSubmitAction] =
    useState<AnnouncementDraftAction>("draft");

  const createMutation = useMutation({
    ...createAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
      router.push(`/dashboard/announcements/${response.announcement.id}`);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถสร้างประกาศได้");
    },
  });

  const updateMutation = useMutation({
    ...updateAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
      router.push(`/dashboard/announcements/${response.announcement.id}`);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถอัปเดตประกาศได้");
    },
  });

  const stateMutation = useMutation({
    ...updateAnnouncementStateMutation,
    onSuccess: (response) => {
      toast.success(response.message);
      router.refresh();
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถอัปเดตสถานะประกาศได้");
    },
  });

  const form = useAppForm({
    defaultValues: {
      title: initialData?.title ?? "",
      content: initialData?.content ?? "",
      startDate: initialData?.start_date
        ? initialData.start_date.slice(0, 10)
        : "",
      endDate: initialData?.end_date ? initialData.end_date.slice(0, 10) : "",
      removeAttachment: false,
    } as AnnouncementFormValues,
    validators: {
      onSubmit: announcementDraftSchema,
    },
    onSubmitInvalid: () => {
      scrollToFirstError();
    },
    onSubmit: async ({ value }) => {
      const payload = {
        title: value.title.trim(),
        content: value.content.trim(),
        startDate: value.startDate,
        endDate: value.endDate?.trim() ? value.endDate : null,
        action: submitAction,
        removeAttachment,
        attachment,
      };

      if (isEdit && initialData) {
        await updateMutation.mutateAsync({
          id: initialData.id,
          values: payload,
        });
        return;
      }

      await createMutation.mutateAsync(payload);
    },
  });

  const isSubmitting =
    createMutation.isPending ||
    updateMutation.isPending ||
    stateMutation.isPending;
  const isOwner = initialData ? initialData.created_by === currentUserId : true;

  const canSubmit = canTransitionContent({
    module: "announcement",
    action: "submit",
    currentStatus: initialData?.status ?? "draft",
    permissions,
    isOwner,
  });
  const canPublish = initialData
    ? canTransitionContent({
        module: "announcement",
        action: "publish",
        currentStatus: initialData.status,
        permissions,
        isOwner,
      })
    : false;
  const canArchive = initialData
    ? canTransitionContent({
        module: "announcement",
        action: "archive",
        currentStatus: initialData.status,
        permissions,
        isOwner,
      })
    : false;
  const showDraftWorkflowActions = !isEdit || canSubmit;
  const canViewReviewNote = initialData
    ? canViewAnnouncementReviewNote({
        announcement: initialData,
      })
    : false;

  function submitWithAction(action: AnnouncementDraftAction) {
    setSubmitAction(action);
    void form.handleSubmit();
  }

  return (
    <Card className="mx-auto w-full">
      <CardHeader className="space-y-3">
        <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
          <div className="space-y-1">
            <CardTitle className="text-2xl">
              {isEdit ? "แก้ไขประกาศ" : "สร้างประกาศ"}
            </CardTitle>
            <CardDescription>
              จัดการรายละเอียดประกาศ ช่วงเวลาแสดงผล ไฟล์แนบ และการเผยแพร่
            </CardDescription>
          </div>

          {isEdit && initialData ? (
            <div className="flex flex-wrap gap-2">
              {canPublish ? (
                <Button
                  type="button"
                  onClick={() =>
                    stateMutation.mutate({
                      id: initialData.id,
                      values: { action: "publish" },
                    })
                  }
                  disabled={isSubmitting}
                >
                  เผยแพร่
                </Button>
              ) : null}
              {canArchive ? (
                <Button
                  type="button"
                  variant="outline"
                  onClick={() =>
                    stateMutation.mutate({
                      id: initialData.id,
                      values: { action: "archive" },
                    })
                  }
                  disabled={isSubmitting}
                >
                  ลบออกประกาศ
                </Button>
              ) : null}
            </div>
          ) : null}
        </div>
      </CardHeader>
      <CardContent>
        <form.AppForm>
          <form.Form className="space-y-6">
            <FormErrors />

            <form.AppField name="title">
              {(field) => (
                <field.FieldSet>
                  <field.Field>
                    <field.FieldLabel htmlFor={field.name}>
                      หัวข้อประกาศ *
                    </field.FieldLabel>
                    <Input
                      id={field.name}
                      value={field.state.value}
                      onChange={(event) =>
                        field.handleChange(event.target.value)
                      }
                      onBlur={field.handleBlur}
                      placeholder="กรอกหัวข้อประกาศ"
                      disabled={isSubmitting}
                    />
                  </field.Field>
                  <field.FieldError />
                </field.FieldSet>
              )}
            </form.AppField>

            <form.AppField name="content">
              {(field) => (
                <field.FieldSet>
                  <field.Field>
                    <field.FieldLabel htmlFor={field.name}>
                      รายละเอียดประกาศ *
                    </field.FieldLabel>
                    <Textarea
                      id={field.name}
                      value={field.state.value}
                      onChange={(event) =>
                        field.handleChange(event.target.value)
                      }
                      onBlur={field.handleBlur}
                      placeholder="กรอกรายละเอียดประกาศ"
                      rows={10}
                      disabled={isSubmitting}
                    />
                  </field.Field>
                  <field.FieldError />
                </field.FieldSet>
              )}
            </form.AppField>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <form.AppField name="startDate">
                {(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel htmlFor={field.name}>
                        วันเริ่มแสดง *
                      </field.FieldLabel>
                      <Input
                        id={field.name}
                        type="date"
                        value={field.state.value ?? ""}
                        onChange={(event) =>
                          field.handleChange(event.target.value)
                        }
                        onBlur={field.handleBlur}
                        disabled={isSubmitting}
                      />
                    </field.Field>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              </form.AppField>

              <form.AppField name="endDate">
                {(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel htmlFor={field.name}>
                        วันสิ้นสุดการแสดง
                      </field.FieldLabel>
                      <Input
                        id={field.name}
                        type="date"
                        value={field.state.value ?? ""}
                        onChange={(event) =>
                          field.handleChange(event.target.value)
                        }
                        onBlur={field.handleBlur}
                        disabled={isSubmitting}
                      />
                    </field.Field>
                    <field.FieldDescription>
                      เว้นว่างได้หากต้องการแสดงประกาศต่อเนื่อง
                    </field.FieldDescription>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              </form.AppField>
            </div>

            <div className="space-y-3 rounded-lg border p-4">
              <div className="space-y-1">
                <div className="text-sm font-medium">ไฟล์แนบ</div>
                <div className="text-muted-foreground text-sm">
                  รองรับ PDF, JPG, JPEG, PNG, DOC, DOCX, XLS และ XLSX
                  ขนาดไม่เกิน 10MB
                </div>
              </div>

              {initialData?.attachment_file_url &&
              !removeAttachment &&
              !attachment ? (
                <div className="flex flex-col gap-3 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between">
                  <div className="min-w-0">
                    <Link
                      href={initialData.attachment_file_url}
                      target="_blank"
                      rel="noreferrer"
                      className="text-primary block truncate text-sm font-medium hover:underline"
                    >
                      {initialData.attachment_file_name ?? "ไฟล์แนบปัจจุบัน"}
                    </Link>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setRemoveAttachment(true)}
                    disabled={isSubmitting}
                  >
                    ลบไฟล์แนบ
                  </Button>
                </div>
              ) : null}

              {removeAttachment &&
              initialData?.attachment_file_url &&
              !attachment ? (
                <div className="flex items-center justify-between rounded-md border border-dashed p-3 text-sm">
                  <span className="text-muted-foreground">
                    ไฟล์เดิมจะถูกลบหลังบันทึก
                  </span>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => setRemoveAttachment(false)}
                    disabled={isSubmitting}
                  >
                    ยกเลิก
                  </Button>
                </div>
              ) : null}

              <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
                <Input
                  ref={fileInputRef}
                  type="file"
                  accept={attachmentAccept}
                  onChange={(event) => {
                    const file = event.target.files?.[0] ?? null;
                    setAttachment(file);
                    if (file) setRemoveAttachment(false);
                  }}
                  disabled={isSubmitting}
                />
                {attachment ? (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setAttachment(null);
                      if (fileInputRef.current) {
                        fileInputRef.current.value = "";
                      }
                    }}
                    disabled={isSubmitting}
                  >
                    ล้างไฟล์ใหม่
                  </Button>
                ) : null}
              </div>

              {attachment ? (
                <div className="text-sm">
                  ไฟล์ที่เลือก:{" "}
                  <span className="font-medium">{attachment.name}</span>
                </div>
              ) : null}
            </div>

            {initialData && hasAnnouncementWorkflowData(initialData) && canViewReviewNote ? (
              <div className="rounded-lg border border-dashed p-4 text-sm">
                <div className="font-medium">หมายเหตุการตรวจสอบ</div>
                <div className="text-muted-foreground mt-1 whitespace-pre-wrap">
                  {initialData.review_comment}
                </div>
              </div>
            ) : null}

            <div className="flex flex-col-reverse gap-2 sm:flex-row sm:flex-wrap sm:justify-end">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push("/dashboard/announcements")}
                className="w-full sm:w-auto"
              >
                ยกเลิก
              </Button>

              {showDraftWorkflowActions ? (
                <>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => submitWithAction("draft")}
                    className="w-full sm:w-auto"
                    disabled={isSubmitting}
                  >
                    {isSubmitting && submitAction === "draft"
                      ? "กำลังบันทึก..."
                      : "บันทึกร่าง"}
                  </Button>
                  {canSubmit ? (
                    <Button
                      type="button"
                      onClick={() => submitWithAction("submit")}
                      className="w-full sm:w-auto"
                      disabled={isSubmitting}
                    >
                      {isSubmitting && submitAction === "submit"
                        ? "กำลังส่งตรวจสอบ..."
                        : "ส่งตรวจสอบ"}
                    </Button>
                  ) : null}
                </>
              ) : (
                <form.SubmitButton
                  className="w-full sm:w-auto"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? "กำลังบันทึก..." : "บันทึกการแก้ไข"}
                </form.SubmitButton>
              )}
            </div>
          </form.Form>
        </form.AppForm>
      </CardContent>
    </Card>
  );
}
