"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Eye,
  Download,
  Users,
  MapPin,
  IndianRupee,
  FileText,
  CheckCircle,
  XCircle,
} from "lucide-react";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { AdminTableToolbar } from "@/components/admin/admin-table-toolbar";
import { AdminActionButton } from "@/components/admin/admin-action-button";
import { AdminTablePagination } from "@/components/admin/admin-table-pagination";
import { useLanguage } from "@/lib/i18n";

type ReportStatus =
  "Draft" | "Submitted" | "Reviewed" | "Approved" | "Rejected";
type ReportStatusFilter = "all" | "active" | "inactive";

type GuideAccount = {
  id?: number | string;
  uuid?: string;
  name?: string;
  email?: string;
  phone?: string;
  profile_image?: string | null;
};

type LocationItem = {
  id?: number | string;
  uuid?: string;
  title?: string;
  title_hi?: string | null;
};

type MonthlyReport = {
  id: number | string;
  guide_id: number | string;
  report_month: string;
  number_of_tours: number;
  tourists_served: number;
  revenue: string | number;
  locations_visited: Array<number | string>;
  locations_resolved?: LocationItem[];
  tourist_feedback?: string | null;
  status: ReportStatus | string;
  reviewed_by?: number | string | null;
  reviewed_at?: string | null;
  review_remarks?: string | null;
  submitted_at?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
  guide?: GuideAccount | null;
  reviewer?: GuideAccount | null;
};

type PaginatedReports = {
  current_page: number;
  data: MonthlyReport[];
  per_page: number;
  total: number;
  from?: number | null;
  to?: number | null;
  last_page?: number;
};

type Summary = {
  total_tourists_served: number;
  total_tours_conducted: number;
  total_revenue: number;
  total_reports: number;
  active_reports: number;
  inactive_reports: number;
};

type ReportsResponse = {
  statusCode: number;
  success: boolean;
  data?: {
    reports?: PaginatedReports;
  };
  message?: string;
  message_hi?: string;
};

type SummaryResponse = {
  statusCode: number;
  success: boolean;
  data?: {
    summary?: Summary;
  };
  message?: string;
  message_hi?: string;
};

type ReportResponse = {
  statusCode: number;
  success: boolean;
  data?:
    | {
        report?: MonthlyReport;
      }
    | Record<string, string[]>
    | [];
  message?: string;
  message_hi?: string;
};

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

const emptySummary: Summary = {
  total_tourists_served: 0,
  total_tours_conducted: 0,
  total_revenue: 0,
  total_reports: 0,
  active_reports: 0,
  inactive_reports: 0,
};

function getAdminToken() {
  const token = localStorage.getItem("auth_token");

  if (!token) {
    throw new Error("Admin token missing. Please login again.");
  }

  return token;
}

function getPageCount(pagination: PaginatedReports) {
  return (
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page))
  );
}

function formatMonth(value?: string | null) {
  if (!value) return "-";
  return value.slice(0, 7);
}

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

function formatCurrency(value: number | string) {
  return `INR ${Number(value || 0).toLocaleString("en-IN")}`;
}

function getStatusBadge(status: string, labels: Record<string, string>) {
  const variants: Record<string, string> = {
    Draft: "bg-gray-100 text-gray-700",
    Submitted: "bg-[var(--theme-surface-strong)] text-[var(--theme-primary)]",
    Reviewed: "bg-green-50 text-green-700",
    Approved: "bg-green-50 text-green-700",
    Rejected: "bg-red-50 text-red-700",
  };

  return (
    <Badge
      className={`${variants[status] || "bg-gray-100 text-gray-700"} gap-1.5 rounded-full px-3 py-1 font-semibold shadow-none`}
    >
      <span className="h-1.5 w-1.5 rounded-full bg-current" />
      {labels[status] || status}
    </Badge>
  );
}

function isMonthlyReport(value: unknown): value is MonthlyReport {
  return (
    !!value &&
    typeof value === "object" &&
    !Array.isArray(value) &&
    "id" in value
  );
}

function getValidationError(data: ReportResponse["data"], field: string) {
  if (
    !data ||
    Array.isArray(data) ||
    typeof data !== "object" ||
    "report" in data
  ) {
    return undefined;
  }

  return (data as Record<string, string[]>)[field]?.[0];
}

function DetailRow({
  label,
  value,
}: {
  label: string;
  value: string | number | null | undefined;
}) {
  return (
    <div className="flex items-start justify-between gap-4 rounded-xl bg-[var(--theme-surface)] px-4 py-3 text-sm">
      <span className="font-medium text-muted-foreground">{label}</span>
      <span className="text-right font-semibold text-foreground">
        {value || "-"}
      </span>
    </div>
  );
}

export default function AdminReportsPage() {
  const { t } = useLanguage();
  const [reports, setReports] = useState<MonthlyReport[]>([]);
  const [pagination, setPagination] =
    useState<PaginatedReports>(emptyPagination);
  const [summary, setSummary] = useState<Summary>(emptySummary);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<ReportStatusFilter>("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedReport, setSelectedReport] = useState<MonthlyReport | null>(
    null,
  );
  const [reviewStatus, setReviewStatus] = useState<
    "Reviewed" | "Approved" | "Rejected"
  >("Reviewed");
  const [reviewRemarks, setReviewRemarks] = useState("");
  const [reviewError, setReviewError] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isSummaryLoading, setIsSummaryLoading] = useState(true);
  const [isDetailLoading, setIsDetailLoading] = useState(false);
  const [isStatusSaving, setIsStatusSaving] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [error, setError] = useState("");
  const statusLabels: Record<string, string> = {
    Draft: t("admin.draft"),
    Submitted: t("common.pending"),
    Reviewed: t("admin.markAsReviewed"),
    Approved: t("common.approved"),
    Rejected: t("common.rejected"),
  };

  const buildParams = useCallback(
    (page = currentPage) => {
      const params = new URLSearchParams({ page: String(page) });
      const search = searchTerm.trim();

      if (search) params.set("search", search);
      if (statusFilter !== "all") params.set("status_group", statusFilter);

      return params;
    },
    [currentPage, searchTerm, statusFilter],
  );

  const fetchSummary = useCallback(async () => {
    setIsSummaryLoading(true);

    try {
      const token = getAdminToken();
      const params = buildParams(1);
      params.delete("page");
      params.delete("status_group");

      const response = await apiRequest(
        apiUrl(`/admin/monthly-reports/summary?${params}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as SummaryResponse;

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

      setSummary(result.data?.summary || emptySummary);
    } catch {
      setSummary(emptySummary);
    } finally {
      setIsSummaryLoading(false);
    }
  }, [buildParams]);

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

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/monthly-reports?${buildParams()}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ReportsResponse;

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

      setReports(result.data?.reports?.data || []);
      setPagination(result.data?.reports || emptyPagination);
    } catch (fetchError) {
      setError(
        fetchError instanceof Error
          ? fetchError.message
          : "Failed to load reports.",
      );
      setReports([]);
      setPagination(emptyPagination);
    } finally {
      setIsLoading(false);
    }
  }, [buildParams]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      fetchReports();
      fetchSummary();
    }, 250);

    return () => window.clearTimeout(timer);
  }, [fetchReports, fetchSummary]);

  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const updateStatusFilter = (value: ReportStatusFilter) => {
    setStatusFilter(value);
    setCurrentPage(1);
  };

  const openDetails = async (report: MonthlyReport) => {
    setSelectedReport(report);
    setReviewStatus("Reviewed");
    setReviewRemarks("");
    setReviewError("");
    setIsDetailLoading(true);

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/monthly-reports/${report.id}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ReportResponse;

      const detailData = result.data;

      if (
        !response.ok ||
        result.success === false ||
        !detailData ||
        !("report" in detailData)
      ) {
        throw new Error(
          getLocalizedApiMessage(result, "Failed to load report details."),
        );
      }

      setSelectedReport(
        isMonthlyReport(detailData.report) ? detailData.report : report,
      );
    } catch (detailError) {
      setError(
        detailError instanceof Error
          ? detailError.message
          : "Failed to load report details.",
      );
    } finally {
      setIsDetailLoading(false);
    }
  };

  const updateStatus = async () => {
    if (!selectedReport) return;

    setIsStatusSaving(true);
    setReviewError("");
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/monthly-reports/${selectedReport.id}/change-status`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            status: reviewStatus,
            review_remarks: reviewRemarks,
          }),
        },
      );
      const result = (await response.json()) as ReportResponse;

      if (!response.ok || result.success === false) {
        setReviewError(getValidationError(result.data, "review_remarks") || "");
        throw new Error(
          getLocalizedApiMessage(result, "Failed to update report status."),
        );
      }

      setSelectedReport(null);
      await Promise.all([fetchReports(), fetchSummary()]);
    } catch (statusError) {
      setError(
        statusError instanceof Error
          ? statusError.message
          : "Failed to update report status.",
      );
    } finally {
      setIsStatusSaving(false);
    }
  };

  const exportCsv = async () => {
    setIsExporting(true);
    setError("");

    try {
      const token = getAdminToken();
      const params = buildParams(1);
      params.delete("page");
      const response = await apiRequest(
        apiUrl(`/admin/monthly-reports/export?${params}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "text/csv",
          },
        },
      );

      if (!response.ok) {
        throw new Error("Failed to export reports.");
      }

      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `guide-monthly-reports-${new Date().toISOString().slice(0, 10)}.csv`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(url);
    } catch (exportError) {
      setError(
        exportError instanceof Error
          ? exportError.message
          : "Failed to export reports.",
      );
    } finally {
      setIsExporting(false);
    }
  };

  const visibleFrom =
    pagination.from ??
    (pagination.total > 0
      ? (pagination.current_page - 1) * pagination.per_page + 1
      : 0);
  const visibleTo =
    pagination.to ??
    Math.min(pagination.total, pagination.current_page * pagination.per_page);

  const currentLocations = useMemo(
    () => selectedReport?.locations_resolved || [],
    [selectedReport],
  );

  return (
    <div className="space-y-6">
      <AdminBreadcrumb current="Monthly Reports" />

      <div className="grid gap-5 md:grid-cols-3">
        <Card className="rounded-2xl border-[var(--theme-border-soft)] bg-white shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between px-6 pb-2 pt-6">
            <CardTitle className="text-base font-medium">
              {t("admin.touristsServed")}
            </CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent className="px-6 pb-7 pt-6">
            <div className="text-3xl font-black">
              {isSummaryLoading
                ? "..."
                : summary.total_tourists_served.toLocaleString("en-IN")}
            </div>
          </CardContent>
        </Card>
        <Card className="rounded-2xl border-[var(--theme-border-soft)] bg-white shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between px-6 pb-2 pt-6">
            <CardTitle className="text-base font-medium">
              {t("admin.toursConducted")}
            </CardTitle>
            <MapPin className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent className="px-6 pb-7 pt-6">
            <div className="text-3xl font-black">
              {isSummaryLoading
                ? "..."
                : summary.total_tours_conducted.toLocaleString("en-IN")}
            </div>
          </CardContent>
        </Card>
        <Card className="rounded-2xl border-[var(--theme-border-soft)] bg-white shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between px-6 pb-2 pt-6">
            <CardTitle className="text-base font-medium">
              {t("admin.totalRevenue")}
            </CardTitle>
            <IndianRupee className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent className="px-6 pb-7 pt-6">
            <div className="text-3xl font-black">
              {isSummaryLoading ? "..." : formatCurrency(summary.total_revenue)}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card className="overflow-hidden rounded-3xl border-[var(--theme-border-soft)] bg-white py-0 shadow-sm">
        <AdminTableToolbar
          stats={[
            {
              label: t("admin.total"),
              count: summary.total_reports,
              icon: <FileText className="h-4 w-4" />,
              active: statusFilter === "all",
              onClick: () => updateStatusFilter("all"),
            },
            {
              label: t("admin.active"),
              count: summary.active_reports,
              icon: <CheckCircle className="h-4 w-4" />,
              tone: "success",
              active: statusFilter === "active",
              onClick: () => updateStatusFilter("active"),
            },
            {
              label: t("admin.inactive"),
              count: summary.inactive_reports,
              icon: <XCircle className="h-4 w-4" />,
              tone: "danger",
              active: statusFilter === "inactive",
              onClick: () => updateStatusFilter("inactive"),
            },
          ]}
          searchValue={searchTerm}
          searchPlaceholder={t("admin.searchReports")}
          onSearchChange={handleSearchChange}
        >
          <Button
            type="button"
            variant="outline"
            className="h-11 rounded-2xl bg-white px-5 font-bold"
            onClick={exportCsv}
            disabled={isExporting}
          >
            <Download className="mr-2 h-4 w-4" />
            {isExporting ? t("admin.exporting") : t("admin.exportCsv")}
          </Button>
        </AdminTableToolbar>
        <CardContent className="p-0">
          {error && (
            <Alert className="m-6 border-red-200 bg-red-50 text-red-700">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("admin.guide")}</TableHead>
                <TableHead>{t("admin.month")}</TableHead>
                <TableHead className="text-center">
                  {t("admin.tourists")}
                </TableHead>
                <TableHead className="text-center">
                  {t("admin.tours")}
                </TableHead>
                <TableHead className="text-center">
                  {t("admin.revenue")}
                </TableHead>
                <TableHead>{t("common.status")}</TableHead>
                <TableHead className="text-right">
                  {t("common.actions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    className="h-28 text-center text-muted-foreground"
                  >
                    {t("admin.loadingReports")}
                  </TableCell>
                </TableRow>
              )}

              {!isLoading &&
                reports.map((report) => (
                  <TableRow key={report.id}>
                    <TableCell>
                      <div>
                        <div className="font-medium">
                          {report.guide?.name || "-"}
                        </div>
                        <div className="text-sm text-muted-foreground">
                          {report.guide?.email || "-"}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">
                        {formatMonth(report.report_month)}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-center font-medium">
                      {report.tourists_served}
                    </TableCell>
                    <TableCell className="text-center font-medium">
                      {report.number_of_tours}
                    </TableCell>
                    <TableCell className="text-center font-medium">
                      {formatCurrency(report.revenue)}
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(report.status, statusLabels)}
                    </TableCell>
                    <TableCell>
                      <div className="flex justify-end gap-2">
                        <AdminActionButton
                          icon={Eye}
                          label={t("common.view")}
                          onClick={() => openDetails(report)}
                        />
                      </div>
                    </TableCell>
                  </TableRow>
                ))}

              {!isLoading && reports.length === 0 && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    className="h-28 text-center text-muted-foreground"
                  >
                    {t("admin.noReportsFound")}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
          <AdminTablePagination
            total={pagination.total}
            pageSize={pagination.per_page}
            currentPage={pagination.current_page}
            totalPages={getPageCount(pagination)}
            from={visibleFrom}
            to={visibleTo}
            isLoading={isLoading}
            onPageChange={setCurrentPage}
          />
        </CardContent>
      </Card>

      <Dialog
        open={Boolean(selectedReport)}
        onOpenChange={(open) => !open && setSelectedReport(null)}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
          {selectedReport && (
            <>
              <DialogHeader>
                <DialogTitle>
                  {t("admin.reportDetails")} -{" "}
                  {formatMonth(selectedReport.report_month)}
                </DialogTitle>
                <DialogDescription>
                  {t("admin.reportDetailsDescription")}
                </DialogDescription>
              </DialogHeader>

              {isDetailLoading ? (
                <div className="rounded-2xl border border-[var(--theme-border-soft)] p-8 text-center text-muted-foreground">
                  {t("admin.loadingReportDetails")}
                </div>
              ) : (
                <div className="space-y-6">
                  <div className="rounded-2xl border border-[var(--theme-border-soft)] p-4">
                    <h3 className="mb-3 font-semibold">
                      {t("admin.guideInformation")}
                    </h3>
                    <div className="grid gap-3 md:grid-cols-2">
                      <DetailRow
                        label={t("admin.guideName")}
                        value={selectedReport.guide?.name}
                      />
                      <DetailRow
                        label={t("admin.guideEmail")}
                        value={selectedReport.guide?.email}
                      />
                      <DetailRow
                        label={t("admin.guidePhone")}
                        value={selectedReport.guide?.phone}
                      />
                      <DetailRow
                        label={t("common.status")}
                        value={
                          statusLabels[selectedReport.status] ||
                          selectedReport.status
                        }
                      />
                    </div>
                  </div>

                  <div className="grid gap-4 md:grid-cols-3">
                    <div className="rounded-lg border p-4 text-center">
                      <Users className="mx-auto mb-2 h-8 w-8 text-blue-500" />
                      <div className="text-2xl font-bold">
                        {selectedReport.tourists_served}
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {t("admin.touristsServed")}
                      </p>
                    </div>
                    <div className="rounded-lg border p-4 text-center">
                      <MapPin className="mx-auto mb-2 h-8 w-8 text-green-500" />
                      <div className="text-2xl font-bold">
                        {selectedReport.number_of_tours}
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {t("admin.toursConducted")}
                      </p>
                    </div>
                    <div className="rounded-lg border p-4 text-center">
                      <IndianRupee className="mx-auto mb-2 h-8 w-8 text-[var(--theme-primary)]" />
                      <div className="text-2xl font-bold">
                        {formatCurrency(selectedReport.revenue)}
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {t("admin.revenue")}
                      </p>
                    </div>
                  </div>

                  <div className="grid gap-3 md:grid-cols-2">
                    <DetailRow
                      label={t("admin.reportMonth")}
                      value={formatMonth(selectedReport.report_month)}
                    />
                    <DetailRow
                      label={t("admin.submittedAt")}
                      value={formatDateTime(selectedReport.submitted_at)}
                    />
                    <DetailRow
                      label={t("admin.reviewedBy")}
                      value={selectedReport.reviewer?.name || "-"}
                    />
                    <DetailRow
                      label={t("admin.reviewedAt")}
                      value={formatDateTime(selectedReport.reviewed_at)}
                    />
                  </div>

                  <div className="rounded-lg border p-4">
                    <h4 className="mb-2 font-medium">
                      {t("admin.locationsVisited")}
                    </h4>
                    <div className="flex flex-wrap gap-2">
                      {currentLocations.map((location) => (
                        <Badge
                          key={location.uuid || location.id}
                          variant="secondary"
                        >
                          {location.title || location.id}
                        </Badge>
                      ))}
                      {currentLocations.length === 0 && (
                        <p className="text-sm text-muted-foreground">
                          {t("admin.noLocationsAvailable")}
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="rounded-lg border p-4">
                    <h4 className="mb-2 font-medium">
                      {t("admin.touristFeedback")}
                    </h4>
                    <p className="text-sm leading-6 text-muted-foreground">
                      {selectedReport.tourist_feedback || "-"}
                    </p>
                  </div>

                  <div className="rounded-lg border p-4">
                    <h4 className="mb-2 font-medium">
                      {t("admin.reviewRemarks")}
                    </h4>
                    <p className="text-sm leading-6 text-muted-foreground">
                      {selectedReport.review_remarks || "-"}
                    </p>
                  </div>

                  <div className="rounded-2xl border border-[var(--theme-border-soft)] p-4">
                    <h3 className="mb-3 font-semibold">
                      {t("admin.reviewWorkflow")}
                    </h3>
                    <div className="grid gap-4 md:grid-cols-2">
                      <div className="space-y-2">
                        <Label htmlFor="report-review-status">
                          {t("common.status")}
                        </Label>
                        <select
                          id="report-review-status"
                          value={reviewStatus}
                          onChange={(event) =>
                            setReviewStatus(
                              event.target.value as
                                "Reviewed" | "Approved" | "Rejected",
                            )
                          }
                          className="h-10 w-full rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-3 text-sm"
                        >
                          <option value="Reviewed">
                            {t("admin.markAsReviewed")}
                          </option>
                          <option value="Approved">{t("admin.approve")}</option>
                          <option value="Rejected">{t("admin.reject")}</option>
                        </select>
                      </div>
                      <div className="space-y-2 md:col-span-2">
                        <Label htmlFor="report-review-remarks">
                          {t("admin.reviewRemarks")}
                        </Label>
                        <Textarea
                          id="report-review-remarks"
                          value={reviewRemarks}
                          onChange={(event) => {
                            setReviewRemarks(event.target.value);
                            setReviewError("");
                          }}
                          rows={3}
                          placeholder={t("admin.addReviewRemarks")}
                          className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                        />
                        {reviewError && (
                          <p className="text-xs font-semibold text-red-600">
                            {reviewError}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setSelectedReport(null)}
                  disabled={isStatusSaving}
                >
                  {t("admin.close")}
                </Button>
                <Button
                  type="button"
                  onClick={updateStatus}
                  disabled={isStatusSaving || isDetailLoading}
                >
                  {isStatusSaving ? t("admin.saving") : t("admin.saveReview")}
                </Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
