"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import {
  CalendarDays,
  CheckCircle,
  FileText,
  Loader2,
  SearchCheck,
  XCircle,
} from "lucide-react";

import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { RequestApplicationSteps } from "@/components/admin/request-application-steps";
import { AdminTablePagination } from "@/components/admin/admin-table-pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";

type ApiDistrict = {
  name?: string | null;
  name_hi?: string | null;
};

type ApiDocumentType =
  | {
      title?: string | null;
      name?: string | null;
      document_type?: string | null;
    }
  | string
  | null;

type GuideDocument = {
  id?: number | string;
  uuid?: string | null;
  title?: string | null;
  name?: string | null;
  original_name?: string | null;
  file_name?: string | null;
  file?: string | null;
  file_path?: string | null;
  file_url?: string | null;
  document_url?: string | null;
  url?: string | null;
  status?: string | null;
  document_type?: ApiDocumentType;
};

type ApiGuide = {
  id?: number | string;
  uuid?: string | null;
  name?: string | null;
  email?: string | null;
  guide_documents?: GuideDocument[];
  documents?: GuideDocument[];
};

type IdentityCardDetail = {
  documented_full_name?: string | null;
  father_name?: string | null;
  mother_name?: string | null;
  date_of_birth?: string | null;
  parmanent_address?: string | null;
  permanent_address?: string | null;
  district?: ApiDistrict | null;
};

type IdentityVerificationRequest = {
  id?: number;
  uuid: string;
  guide_id?: number | string | null;
  status?: string | null;
  created_at?: string | null;
  guide?: ApiGuide | null;
  guide_documents?: GuideDocument[];
  supporting_documents?: GuideDocument[];
  documents?: GuideDocument[];
  identity_card_detail?: IdentityCardDetail | null;
};

type Pagination<T> = {
  current_page: number;
  data: T[];
  per_page: number;
  total: number;
  from?: number | null;
  to?: number | null;
  last_page?: number;
};

type ListResponse = {
  statusCode?: number;
  success?: boolean;
  data?: Pagination<IdentityVerificationRequest>;
  message?: string;
  message_hi?: string;
};

type ActionResponse = {
  success?: boolean;
  message?: string;
  message_hi?: string;
};

type DetailResponse = {
  success?: boolean;
  data?:
    | IdentityVerificationRequest
    | {
        request?: IdentityVerificationRequest;
        identity_verification_request?: IdentityVerificationRequest;
      };
  message?: string;
  message_hi?: string;
};

type IssueAction = IdentityVerificationRequest | null;

type ReviewAction = {
  request: IdentityVerificationRequest;
  status: "approved" | "rejected";
} | null;

const emptyPagination: Pagination<IdentityVerificationRequest> = {
  current_page: 1,
  data: [],
  per_page: 10,
  total: 0,
  from: null,
  to: null,
  last_page: 1,
};

function getAdminToken() {
  const token = localStorage.getItem("auth_token");
  if (!token) throw new Error("Admin token missing. Please login again.");
  return token;
}

function formatDate(value?: string | null) {
  if (!value) return "-";
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString();
}

function toDateInputValue(date: Date) {
  return date.toISOString().slice(0, 10);
}

function addYearsToDateInput(value: string, years: number) {
  if (!value) return "";

  const date = new Date(`${value}T00:00:00`);
  if (Number.isNaN(date.getTime())) return "";

  date.setFullYear(date.getFullYear() + years);
  return toDateInputValue(date);
}
function getPageCount(pagination: Pagination<IdentityVerificationRequest>) {
  return (
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page))
  );
}

function getRequestFromResponse(
  result: DetailResponse,
): IdentityVerificationRequest | null {
  if (!result.data) return null;

  if ("uuid" in result.data) {
    return result.data;
  }

  return (
    result.data.request || result.data.identity_verification_request || null
  );
}

function getDocumentTypeLabel(document: GuideDocument) {
  if (typeof document.document_type === "string") return document.document_type;

  return (
    document.document_type?.title ||
    document.document_type?.name ||
    document.document_type?.document_type ||
    ""
  );
}

function getDocumentName(document: GuideDocument) {
  return (
    document.original_name ||
    document.file_name ||
    document.title ||
    document.name ||
    getDocumentTypeLabel(document) ||
    "Uploaded document"
  );
}

function getDocumentSource(document: GuideDocument) {
  return (
    document.file_url ||
    document.document_url ||
    document.url ||
    document.file_path ||
    document.file ||
    ""
  );
}

function getAllDocuments(request: IdentityVerificationRequest | null) {
  if (!request) return [];

  const documents = [
    ...(request.guide_documents || []),
    ...(request.supporting_documents || []),
    ...(request.documents || []),
    ...(request.guide?.guide_documents || []),
    ...(request.guide?.documents || []),
  ];

  const seen = new Set<string>();
  return documents.filter((document, index) => {
    const key =
      document.uuid ||
      String(document.id || "") ||
      getDocumentSource(document) ||
      `${getDocumentName(document)}-${index}`;

    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

function normalizeDocumentStatus(status?: string | null) {
  return String(status || "pending")
    .trim()
    .toLowerCase();
}

function isDocumentApproved(status?: string | null) {
  return ["approved", "accepted", "verified", "active"].includes(
    normalizeDocumentStatus(status),
  );
}

function getDocumentApprovalBlockMessage(documents: GuideDocument[]) {
  if (documents.length === 0) {
    return "Please review and accept uploaded documents before approving this request.";
  }

  const blockedDocument = documents.find(
    (document) => !isDocumentApproved(document.status),
  );

  if (!blockedDocument) return "";

  const status = normalizeDocumentStatus(blockedDocument.status).replace(
    /[-_]/g,
    " ",
  );

  return `Please accept all documents before approving this request. ${getDocumentName(
    blockedDocument,
  )} is ${status}.`;
}

export default function UnderReviewApplicationsPage() {
  const router = useRouter();
  const [pagination, setPagination] = useState(emptyPagination);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [updating, setUpdating] = useState({ uuid: "", status: "" });
  const [reviewAction, setReviewAction] = useState<ReviewAction>(null);
  const [issueAction, setIssueAction] = useState<IssueAction>(null);
  const [issueDate, setIssueDate] = useState("");
  const [validUptoDate, setValidUptoDate] = useState("");
  const [isIssuing, setIsIssuing] = useState(false);
  const [adminRemarks, setAdminRemarks] = useState("");
  const [rejectReason, setRejectReason] = useState("");

  const requests = pagination.data;
  const queryParams = useMemo(() => {
    const params = new URLSearchParams({
      status: "in-review",
      page: String(page),
      per_page: "10",
    });

    return params.toString();
  }, [page]);

  const loadRequests = useCallback(async () => {
    setIsLoading(true);
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/identity-verification-requests?${queryParams}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ListResponse;

      if (!response.ok || result.success === false || !result.data) {
        throw new Error(
          getLocalizedApiMessage(
            result,
            "Failed to load under review applications.",
          ),
        );
      }

      setPagination(result.data);
    } catch (loadError) {
      const message =
        loadError instanceof Error
          ? loadError.message
          : "Failed to load under review applications.";
      setError(message);
      setPagination(emptyPagination);
    } finally {
      setIsLoading(false);
    }
  }, [queryParams]);

  useEffect(() => {
    loadRequests();
  }, [loadRequests]);

  const fetchRequestDetail = async (requestUuid: string) => {
    const response = await apiRequest(
      apiUrl(
        `/admin/identity-verification-requests/${encodeURIComponent(
          requestUuid,
        )}`,
      ),
      {
        headers: {
          Authorization: `Bearer ${getAdminToken()}`,
          Accept: "application/json",
        },
      },
    );
    const result = (await response.json()) as DetailResponse;
    const nextRequest = getRequestFromResponse(result);

    if (!response.ok || result.success === false || !nextRequest) {
      throw new Error(
        getLocalizedApiMessage(result, "Failed to check document status."),
      );
    }

    return nextRequest;
  };

  const getApprovalReadyRequest = async (
    request: IdentityVerificationRequest,
  ) => {
    const nextRequest = await fetchRequestDetail(request.uuid);
    const blockMessage = getDocumentApprovalBlockMessage(
      getAllDocuments(nextRequest),
    );

    if (blockMessage) {
      toast.error(blockMessage);
      return null;
    }

    return nextRequest;
  };

  const openIssueDialog = async (request: IdentityVerificationRequest) => {
    if (!request.uuid) {
      toast.error("Request UUID not found.");
      return;
    }

    setUpdating({ uuid: request.uuid, status: "approved" });

    try {
      const readyRequest = await getApprovalReadyRequest(request);
      if (!readyRequest) return;

      const today = toDateInputValue(new Date());
      setIssueAction(readyRequest);
      setIssueDate(today);
      setValidUptoDate(addYearsToDateInput(today, 5));
    } catch (approvalError) {
      toast.error(
        approvalError instanceof Error
          ? approvalError.message
          : "Failed to check document status.",
      );
    } finally {
      setUpdating({ uuid: "", status: "" });
    }
  };

  const closeIssueDialog = () => {
    if (isIssuing) return;
    setIssueAction(null);
    setIssueDate("");
    setValidUptoDate("");
  };

  const handleIssueDateChange = (value: string) => {
    setIssueDate(value);
    setValidUptoDate(addYearsToDateInput(value, 5));
  };

  const issueIdCard = async () => {
    if (!issueAction) return;
    if (!issueDate || !validUptoDate) {
      toast.error("Issue date and valid upto date are required.");
      return;
    }

    setIsIssuing(true);
    setUpdating({ uuid: issueAction.uuid, status: "approved" });

    try {
      const readyRequest = await getApprovalReadyRequest(issueAction);
      if (!readyRequest) return;
      setIssueAction(readyRequest);

      const token = getAdminToken();
      const approveResponse = await apiRequest(
        apiUrl(
          `/admin/identity-verification-requests/${encodeURIComponent(
            issueAction.uuid,
          )}/change-status`,
        ),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            status: "approved",
            admin_remarks: "Approved while issuing ID card.",
          }),
        },
      );
      const approveResult = (await approveResponse.json()) as ActionResponse;

      if (!approveResponse.ok || approveResult.success === false) {
        throw new Error(
          getLocalizedApiMessage(approveResult, "Failed to approve request."),
        );
      }

      const issueResponse = await apiRequest(
        apiUrl(
          `/admin/identity-verification-requests/${encodeURIComponent(
            issueAction.uuid,
          )}/issue-id-card`,
        ),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            issue_date: issueDate,
            valid_upto: validUptoDate,
          }),
        },
      );
      const issueResult = (await issueResponse.json()) as ActionResponse;

      if (!issueResponse.ok || issueResult.success === false) {
        throw new Error(
          getLocalizedApiMessage(issueResult, "Failed to issue ID card."),
        );
      }

      toast.success(
        getLocalizedApiMessage(issueResult, "ID card issued successfully."),
      );
      closeIssueDialog();
      router.push(
        "/admin/guide-requests/completed-applications?status=approved",
      );
    } catch (issueError) {
      toast.error(
        issueError instanceof Error
          ? issueError.message
          : "Failed to issue ID card.",
      );
    } finally {
      setIsIssuing(false);
      setUpdating({ uuid: "", status: "" });
    }
  };
  const openReviewDialog = (
    request: IdentityVerificationRequest,
    status: "approved" | "rejected",
  ) => {
    if (!request.uuid) {
      toast.error("Request UUID not found.");
      return;
    }

    setReviewAction({ request, status });
    setAdminRemarks("");
    setRejectReason("");
  };

  const closeReviewDialog = () => {
    if (updating.uuid) return;
    setReviewAction(null);
    setAdminRemarks("");
    setRejectReason("");
  };

  const changeStatus = async () => {
    if (!reviewAction) return;

    const { request, status } = reviewAction;

    if (!request.uuid) {
      toast.error("Request UUID not found.");
      return;
    }

    setUpdating({ uuid: request.uuid, status });

    try {
      if (status === "approved") {
        const readyRequest = await getApprovalReadyRequest(request);
        if (!readyRequest) return;
      }

      const body: Record<string, string> = { status };
      const trimmedRemarks = adminRemarks.trim();
      const trimmedRejectReason = rejectReason.trim();

      if (trimmedRemarks) body.admin_remarks = trimmedRemarks;
      if (status === "rejected") body.reject_reason = trimmedRejectReason;

      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(
          `/admin/identity-verification-requests/${encodeURIComponent(
            request.uuid,
          )}/change-status`,
        ),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        },
      );
      const result = (await response.json()) as ActionResponse;

      if (!response.ok || result.success === false) {
        toast.error(
          getLocalizedApiMessage(result, `Failed to ${status} request.`),
        );
        return;
      }

      toast.success(getLocalizedApiMessage(result, `Request ${status}.`));
      setReviewAction(null);
      setAdminRemarks("");
      setRejectReason("");
      router.push(
        `/admin/guide-requests/completed-applications?status=${status}`,
      );
    } catch {
      toast.error("Unable to connect to the verification request server.");
    } finally {
      setUpdating({ uuid: "", status: "" });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between">
        <AdminBreadcrumb
          parent="Guide Requests"
          parentHref="/admin/guide-requests/new-applications"
          current="Under Review"
        />
        <RequestApplicationSteps activeStep="review" hiddenSteps={["issued"]} />
      </div>

      <Card className="overflow-hidden rounded-3xl border-[var(--theme-border-soft)] bg-white py-0 shadow-sm">
        <CardHeader className="border-b border-[var(--theme-border-soft)] px-6 py-5">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <CardTitle className="flex items-center gap-2 text-2xl font-black">
                <SearchCheck className="h-6 w-6 text-[var(--theme-primary)]" />
                Under Review
              </CardTitle>
              <p className="mt-1 text-sm font-medium text-muted-foreground">
                Identity verification requests currently under department
                review.
              </p>
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {error && (
            <div className="m-6 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-700">
              {error}
            </div>
          )}

          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="min-w-[180px]">Guide Name</TableHead>
                  <TableHead className="min-w-[200px]">
                    Documented Name
                  </TableHead>
                  <TableHead className="min-w-[220px]">
                    Official Email
                  </TableHead>
                  <TableHead className="min-w-[160px]">Father Name</TableHead>
                  <TableHead className="min-w-[160px]">Mother Name</TableHead>
                  <TableHead className="min-w-[140px]">Date of Birth</TableHead>
                  <TableHead className="min-w-[260px]">
                    Permanent Address
                  </TableHead>
                  <TableHead className="min-w-[140px]">Created On</TableHead>
                  <TableHead className="min-w-[180px]">
                    Document Verification
                  </TableHead>
                  <TableHead className="min-w-[180px] text-right">
                    Verification Process
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading && (
                  <TableRow>
                    <TableCell
                      colSpan={10}
                      className="h-32 text-center text-muted-foreground"
                    >
                      <Loader2 className="mx-auto mb-3 h-8 w-8 animate-spin text-[var(--theme-primary)]" />
                      Loading under review applications...
                    </TableCell>
                  </TableRow>
                )}

                {!isLoading &&
                  requests.map((request) => {
                    const detail = request.identity_card_detail;

                    return (
                      <TableRow key={request.uuid || request.id}>
                        <TableCell className="font-semibold">
                          {request.guide?.name || "-"}
                        </TableCell>
                        <TableCell>
                          {detail?.documented_full_name || "-"}
                        </TableCell>
                        <TableCell>{request.guide?.email || "-"}</TableCell>
                        <TableCell>{detail?.father_name || "-"}</TableCell>
                        <TableCell>{detail?.mother_name || "-"}</TableCell>
                        <TableCell>
                          {formatDate(detail?.date_of_birth)}
                        </TableCell>
                        <TableCell>
                          <div className="space-y-2">
                            {detail?.district?.name && (
                              <Badge
                                variant="outline"
                                className="rounded-full border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-primary)]"
                              >
                                {detail.district.name}
                              </Badge>
                            )}
                            <span className="line-clamp-2">
                              {detail?.parmanent_address ||
                                detail?.permanent_address ||
                                "-"}
                            </span>
                          </div>
                        </TableCell>
                        <TableCell>{formatDate(request.created_at)}</TableCell>
                        <TableCell>
                          {request.uuid ? (
                            <Button
                              type="button"
                              size="sm"
                              variant="outline"
                              className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)] font-bold text-[var(--theme-primary)] hover:bg-[var(--theme-surface-strong)]"
                              asChild
                            >
                              <Link
                                href={`/admin/guide-requests/under-review/${request.uuid}/documents`}
                              >
                                <FileText className="mr-2 h-4 w-4" />
                                View Documents
                              </Link>
                            </Button>
                          ) : (
                            <span className="text-sm text-muted-foreground">
                              -
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              type="button"
                              size="sm"
                              className="rounded-xl bg-green-600 font-bold text-white hover:bg-green-700"
                              disabled={updating.uuid === request.uuid}
                              onClick={() => openIssueDialog(request)}
                            >
                              {updating.uuid === request.uuid &&
                              updating.status === "approved" ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              ) : (
                                <CheckCircle className="mr-2 h-4 w-4" />
                              )}
                              Approve
                            </Button>
                            <Button
                              type="button"
                              size="sm"
                              variant="outline"
                              className="rounded-xl border-red-200 bg-red-50 font-bold text-red-700 hover:bg-red-100 hover:text-red-700"
                              disabled={updating.uuid === request.uuid}
                              onClick={() =>
                                openReviewDialog(request, "rejected")
                              }
                            >
                              {updating.uuid === request.uuid &&
                              updating.status === "rejected" ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              ) : (
                                <XCircle className="mr-2 h-4 w-4" />
                              )}
                              Reject
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}

                {!isLoading && requests.length === 0 && (
                  <TableRow>
                    <TableCell
                      colSpan={10}
                      className="h-32 text-center text-muted-foreground"
                    >
                      No under review applications found.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          <AdminTablePagination
            total={pagination.total}
            pageSize={pagination.per_page}
            currentPage={pagination.current_page}
            totalPages={getPageCount(pagination)}
            from={pagination.from}
            to={pagination.to}
            isLoading={isLoading}
            onPageChange={setPage}
          />
        </CardContent>
      </Card>

      <Dialog
        open={Boolean(issueAction)}
        onOpenChange={(open) => {
          if (!open) closeIssueDialog();
        }}
      >
        <DialogContent className="rounded-3xl border-[var(--theme-border-soft)] sm:max-w-xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-xl font-black">
              <CalendarDays className="h-5 w-5 text-[var(--theme-primary)]" />
              Issue ID Card
            </DialogTitle>
            <DialogDescription>
              {issueAction?.guide?.name ||
                issueAction?.identity_card_detail?.documented_full_name ||
                "Selected request"}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4 text-sm leading-6 text-muted-foreground">
              Approving this request will issue the guide ID card using the
              selected issue and validity dates.
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="under-review-issue-date">Issue Date</Label>
                <Input
                  id="under-review-issue-date"
                  type="date"
                  value={issueDate}
                  onChange={(event) =>
                    handleIssueDateChange(event.target.value)
                  }
                  className="h-11 rounded-2xl border-[var(--theme-border-soft)]"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="under-review-valid-upto-date">
                  Valid Upto Date
                </Label>
                <Input
                  id="under-review-valid-upto-date"
                  type="date"
                  value={validUptoDate}
                  onChange={(event) => setValidUptoDate(event.target.value)}
                  className="h-11 rounded-2xl border-[var(--theme-border-soft)]"
                />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              className="rounded-xl border-[var(--theme-border-soft)] bg-white"
              disabled={isIssuing}
              onClick={closeIssueDialog}
            >
              Cancel
            </Button>
            <Button
              type="button"
              className="rounded-xl bg-green-600 font-bold text-white hover:bg-green-700"
              disabled={isIssuing || !issueDate || !validUptoDate}
              onClick={issueIdCard}
            >
              {isIssuing ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <CheckCircle className="mr-2 h-4 w-4" />
              )}
              Issue ID Card
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog
        open={Boolean(reviewAction)}
        onOpenChange={(open) => {
          if (!open) closeReviewDialog();
        }}
      >
        <DialogContent className="rounded-3xl border-[var(--theme-border-soft)] sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="text-xl font-black">
              {reviewAction?.status === "approved"
                ? "Approve Request"
                : "Reject Request"}
            </DialogTitle>
            <DialogDescription>
              {reviewAction?.request.guide?.name ||
                reviewAction?.request.identity_card_detail
                  ?.documented_full_name ||
                "Selected request"}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {reviewAction?.status === "rejected" && (
              <div className="space-y-2">
                <Label htmlFor="reject_reason">
                  Reject Reason <span className="text-red-600">*</span>
                </Label>
                <Textarea
                  id="reject_reason"
                  value={rejectReason}
                  onChange={(event) => setRejectReason(event.target.value)}
                  placeholder="Enter reject reason"
                  className="min-h-28 rounded-2xl border-[var(--theme-border-soft)]"
                  required
                />
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="admin_remarks">
                Remarks
                <span className="ml-1 text-xs font-medium text-muted-foreground">
                  Optional
                </span>
              </Label>
              <Textarea
                id="admin_remarks"
                value={adminRemarks}
                onChange={(event) => setAdminRemarks(event.target.value)}
                placeholder="Add remarks"
                className="min-h-28 rounded-2xl border-[var(--theme-border-soft)]"
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              className="rounded-xl border-[var(--theme-border-soft)] bg-white"
              disabled={Boolean(updating.uuid)}
              onClick={closeReviewDialog}
            >
              Cancel
            </Button>
            <Button
              type="button"
              className={
                reviewAction?.status === "rejected"
                  ? "rounded-xl bg-red-600 font-bold text-white hover:bg-red-700"
                  : "rounded-xl bg-green-600 font-bold text-white hover:bg-green-700"
              }
              disabled={
                Boolean(updating.uuid) ||
                (reviewAction?.status === "rejected" && !rejectReason.trim())
              }
              onClick={changeStatus}
            >
              {updating.uuid ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : reviewAction?.status === "rejected" ? (
                <XCircle className="h-4 w-4" />
              ) : (
                <CheckCircle className="h-4 w-4" />
              )}
              {reviewAction?.status === "rejected" ? "Reject" : "Approve"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
