"use client";

import Link from "next/link";
import { useState } from "react";
import { notFound } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { Icons } from "@/components/icons";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { ContentReviewActionDialog } from "@/features/content-approval/components/content-review-action-dialog";
import {
  canEditContent,
  canTransitionContent,
} from "@/features/content-approval/lib/workflow";
import {
  pinAnnouncementMutation,
  unpinAnnouncementMutation,
  updateAnnouncementStateMutation,
} from "../api/mutations";
import { announcementByIdOptions } from "../api/queries";
import {
  canManageAnnouncementPin,
  isAnnouncementPinEligible,
} from "../lib/pin";
import {
  canViewAnnouncementReviewNote,
  hasAnnouncementWorkflowData,
} from "../lib/workflow-visibility";
import { AnnouncementStatusBadge } from "./announcement-status-badge";
import AnnouncementForm from "./announcement-form";

export default function AnnouncementViewPage({
  announcementId,
  currentUserId,
  permissions,
}: {
  announcementId: string;
  currentUserId: string;
  permissions: readonly string[];
}) {
  if (announcementId === "new") {
    return (
      <AnnouncementForm
        initialData={null}
        permissions={permissions}
        currentUserId={currentUserId}
      />
    );
  }

  return (
    <AnnouncementLoadedView
      announcementId={Number(announcementId)}
      currentUserId={currentUserId}
      permissions={permissions}
    />
  );
}

function AnnouncementLoadedView({
  announcementId,
  currentUserId,
  permissions,
}: {
  announcementId: number;
  currentUserId: string;
  permissions: readonly string[];
}) {
  const [reviewAction, setReviewAction] = useState<
    "approve" | "return" | "reject" | null
  >(null);
  const { data, error, isPending } = useQuery(
    announcementByIdOptions(announcementId),
  );
  const stateMutation = useMutation(updateAnnouncementStateMutation);
  const pinMutation = useMutation({
    ...pinAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถปักหมุดประกาศได้");
    },
  });
  const unpinMutation = useMutation({
    ...unpinAnnouncementMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || "ไม่สามารถยกเลิกการปักหมุดได้");
    },
  });

  if (isPending) {
    return (
      <Card className="border-dashed">
        <CardContent className="flex flex-col items-center justify-center gap-4 py-12 text-center">
          <Icons.spinner className="text-muted-foreground h-6 w-6 animate-spin" />
          <p className="text-muted-foreground text-sm">
            กำลังโหลดรายละเอียดประกาศ
          </p>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    if (error.message.includes("ไม่พบประกาศ")) {
      notFound();
    }

    return (
      <Alert variant="destructive">
        <Icons.warning className="h-4 w-4" />
        <AlertTitle>ไม่สามารถโหลดรายละเอียดประกาศได้</AlertTitle>
        <AlertDescription>{error.message}</AlertDescription>
      </Alert>
    );
  }

  if (!data?.announcement) {
    notFound();
  }

  const announcement = data.announcement;
  const isOwner = announcement.created_by === currentUserId;
  const canEdit = canEditContent({
    module: "announcement",
    permissions,
    status: announcement.status,
    isOwner,
  });

  if (canEdit) {
    return (
      <AnnouncementForm
        initialData={announcement}
        permissions={permissions}
        currentUserId={currentUserId}
      />
    );
  }

  const canApprove = canTransitionContent({
    module: "announcement",
    action: "approve",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canReturn = canTransitionContent({
    module: "announcement",
    action: "return",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canReject = canTransitionContent({
    module: "announcement",
    action: "reject",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canPublish = canTransitionContent({
    module: "announcement",
    action: "publish",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canArchive = canTransitionContent({
    module: "announcement",
    action: "archive",
    currentStatus: announcement.status,
    permissions,
    isOwner,
  });
  const canPinManage = canManageAnnouncementPin(permissions);
  const canPin =
    canPinManage &&
    !announcement.is_pin &&
    isAnnouncementPinEligible(announcement);
  const canUnpin = canPinManage && announcement.is_pin;
  const canViewReviewNote = canViewAnnouncementReviewNote({
    announcement,
  });

  return (
    <>
      <ContentReviewActionDialog
        open={reviewAction !== null}
        onOpenChange={(open) => {
          if (!open) {
            setReviewAction(null);
          }
        }}
        action={reviewAction}
        module="announcement"
        contentTitle={announcement.title}
        isSubmitting={stateMutation.isPending}
        onConfirm={(values) => {
          stateMutation.mutate({ id: announcement.id, values });
          setReviewAction(null);
        }}
      />

      <Card>
        <CardHeader className="space-y-4">
          <div className="flex flex-wrap items-center gap-2">
            {announcement.is_pin ? (
              <span className="rounded-full border px-2 py-0.5 text-xs">
                ปักหมุด
              </span>
            ) : null}
            <AnnouncementStatusBadge status={announcement.status} />
          </div>
          <div className="min-w-0 space-y-2">
            <CardTitle className="text-2xl">{announcement.title}</CardTitle>
            <CardDescription className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
              <span>
                เริ่มแสดง{" "}
                {new Date(announcement.start_date).toLocaleDateString("th-TH")}
              </span>
              <span>
                สิ้นสุด{" "}
                {announcement.end_date
                  ? new Date(announcement.end_date).toLocaleDateString("th-TH")
                  : "ไม่กำหนด"}
              </span>
              <span>ประกาศโดย {announcement.created_by_name ?? "-"}</span>
            </CardDescription>
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          {canApprove ||
          canReturn ||
          canReject ||
          canPublish ||
          canArchive ||
          canPin ||
          canUnpin ? (
            <div className="flex flex-wrap gap-2">
              {canApprove ? (
                <Button
                  onClick={() => setReviewAction("approve")}
                  disabled={stateMutation.isPending}
                >
                  อนุมัติ
                </Button>
              ) : null}
              {canReturn ? (
                <Button
                  variant="outline"
                  onClick={() => setReviewAction("return")}
                  disabled={stateMutation.isPending}
                >
                  ส่งกลับ
                </Button>
              ) : null}
              {canReject ? (
                <Button
                  variant="outline"
                  onClick={() => setReviewAction("reject")}
                  disabled={stateMutation.isPending}
                >
                  ไม่อนุมัติ
                </Button>
              ) : null}
              {canPublish ? (
                <Button
                  onClick={() =>
                    stateMutation.mutate({
                      id: announcement.id,
                      values: { action: "publish" },
                    })
                  }
                  disabled={stateMutation.isPending}
                >
                  เผยแพร่
                </Button>
              ) : null}
              {canArchive ? (
                <Button
                  variant="outline"
                  onClick={() =>
                    stateMutation.mutate({
                      id: announcement.id,
                      values: { action: "archive" },
                    })
                  }
                  disabled={stateMutation.isPending}
                >
                  ยกเลิกเผยแพร่
                </Button>
              ) : null}
              {canPin ? (
                <Button
                  variant="outline"
                  onClick={() => pinMutation.mutate(announcement.id)}
                  disabled={stateMutation.isPending || pinMutation.isPending}
                >
                  ปักหมุด
                </Button>
              ) : null}
              {canUnpin ? (
                <Button
                  variant="outline"
                  onClick={() => unpinMutation.mutate(announcement.id)}
                  disabled={stateMutation.isPending || unpinMutation.isPending}
                >
                  ยกเลิกปักหมุด
                </Button>
              ) : null}
            </div>
          ) : null}

          <div className="whitespace-pre-wrap text-sm leading-7">
            {announcement.content}
          </div>

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

          {announcement.attachment_file_url ? (
            <div className="rounded-lg border p-4">
              <div className="mb-2 text-sm font-medium">ไฟล์แนบ</div>
              <Button asChild variant="outline" className="w-full sm:w-auto">
                <Link
                  href={announcement.attachment_file_url}
                  target="_blank"
                  rel="noreferrer"
                >
                  <Icons.paperclip className="h-4 w-4" />
                  {announcement.attachment_file_name ?? "เปิดไฟล์แนบ"}
                </Link>
              </Button>
            </div>
          ) : null}
        </CardContent>
      </Card>
    </>
  );
}
