"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import { ClipboardList, Loader2, SearchCheck } 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";

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

type ApiGuide = {
  name?: string | null;
  email?: string | null;
};

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;
  status?: string | null;
  created_at?: string | null;
  guide?: ApiGuide | null;
  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;
};

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 getPageCount(pagination: Pagination<IdentityVerificationRequest>) {
  return (
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page))
  );
}

export default function NewApplicationsPage() {
  const router = useRouter();
  const [pagination, setPagination] = useState(emptyPagination);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [updatingUuid, setUpdatingUuid] = useState("");

  const requests = pagination.data;
  const queryParams = useMemo(() => {
    const params = new URLSearchParams({
      status: "pending",
      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 new applications."),
        );
      }

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

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

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

    setUpdatingUuid(request.uuid);

    try {
      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({ status: "in-review" }),
        },
      );
      const result = (await response.json()) as ActionResponse;

      if (!response.ok || result.success === false) {
        toast.error(
          getLocalizedApiMessage(result, "Failed to move request in review."),
        );
        return;
      }

      toast.success(getLocalizedApiMessage(result, "Request moved in review."));
      router.push("/admin/guide-requests/under-review");
    } catch {
      toast.error("Unable to connect to the verification request server.");
    } finally {
      setUpdatingUuid("");
    }
  };

  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="New Applications"
        />
        <RequestApplicationSteps activeStep="new" 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">
                <ClipboardList className="h-6 w-6 text-[var(--theme-primary)]" />
                New Applications
              </CardTitle>
              <p className="mt-1 text-sm font-medium text-muted-foreground">
                Pending identity verification requests from guides.
              </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-[140px] text-right">
                    Action
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading && (
                  <TableRow>
                    <TableCell
                      colSpan={9}
                      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 new 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 className="text-right">
                          <Button
                            type="button"
                            size="sm"
                            className="rounded-xl bg-[var(--theme-primary)] font-bold hover:bg-[var(--theme-accent-dark)]"
                            disabled={updatingUuid === request.uuid}
                            onClick={() => markInReview(request)}
                          >
                            {updatingUuid === request.uuid ? (
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                              <SearchCheck className="mr-2 h-4 w-4" />
                            )}
                            In Review
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}

                {!isLoading && requests.length === 0 && (
                  <TableRow>
                    <TableCell
                      colSpan={9}
                      className="h-32 text-center text-muted-foreground"
                    >
                      No new 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>
    </div>
  );
}
