"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ChevronDown, Inbox, Loader2, Mail } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils/cn";
import { inquiryAdminApi } from "@/lib/api/client";

type InquiryStatus = "NEW" | "REVIEWED" | "CLOSED";

interface Inquiry {
  id: string;
  type: string;
  name: string;
  email: string;
  subject?: string;
  message: string;
  detailsJson?: string;
  status: InquiryStatus;
  adminNote?: string;
  createdAt: string;
}

/** Every form on the public site posts one of these. */
const TYPE_LABELS: Record<string, string> = {
  CONTACT: "संपर्क / Contact",
  FEEDBACK: "प्रतिक्रिया / Feedback",
  SEMINAR: "सेमिनार / Seminar",
  WORKSHOP: "कार्यशाला / Workshop",
  TRAINING: "प्रशिक्षण / Training",
  BOOK_SUGGESTION: "पुस्तक सुझाव / Book suggestion",
  TOPIC_SUGGESTION: "विषय सुझाव / Topic suggestion",
  ABSTRACT: "शोध सारांश / Abstract",
  SUBSCRIPTION: "सदस्यता / Subscription",
  FORUM: "मंच / Forum",
};

const STATUSES: { value: InquiryStatus | "ALL"; label: string }[] = [
  { value: "ALL", label: "सभी / All" },
  { value: "NEW", label: "नई / New" },
  { value: "REVIEWED", label: "देखी गई / Reviewed" },
  { value: "CLOSED", label: "बंद / Closed" },
];

const STATUS_STYLE: Record<InquiryStatus, string> = {
  NEW: "bg-amber-100 text-amber-800",
  REVIEWED: "bg-indigo-100 text-indigo-700",
  CLOSED: "bg-gray-100 text-gray-600",
};

function when(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleString("en-GB", {
    day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit",
  });
}

export default function AdminInquiriesPage() {
  const queryClient = useQueryClient();
  const [filter, setFilter] = useState<InquiryStatus | "ALL">("NEW");
  const [page, setPage] = useState(0);
  const [openId, setOpenId] = useState<string | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["admin-inquiries", filter, page],
    queryFn: async () => {
      const res = await inquiryAdminApi.list({
        status: filter === "ALL" ? undefined : filter,
        page,
        size: 20,
      });
      return res.data as { content: Inquiry[]; totalElements: number; totalPages: number };
    },
  });

  const items = data?.content ?? [];

  return (
    <div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">
          पूछताछ <span className="text-lg font-normal text-gray-400">/ Inquiries</span>
        </h1>
        <p className="mt-0.5 text-sm text-gray-500">
          सार्वजनिक वेबसाइट के सभी प्रपत्रों से प्राप्त संदेश — संपर्क, सदस्यता, सेमिनार, कार्यशाला एवं प्रशिक्षण
        </p>
        {/* No mail goes out when one of these arrives; this screen is where they
            are read. Saying so beats an editor wondering why his inbox is empty. */}
        <p className="mt-2 rounded-lg bg-indigo-50 px-3 py-2 text-xs text-indigo-800">
          इन संदेशों की सूचना ई-मेल से नहीं भेजी जाती। उत्तर देने हेतु नीचे दिए गए ई-मेल पते का उपयोग करें।
          <span className="text-indigo-600"> / These are not emailed anywhere — reply using the sender&rsquo;s address below.</span>
        </p>
      </div>

      <div className="mb-4 flex flex-wrap gap-2">
        {STATUSES.map((s) => (
          <button
            key={s.value}
            onClick={() => { setFilter(s.value); setPage(0); }}
            className={cn(
              "rounded-xl px-4 py-2 text-xs font-medium transition-colors",
              filter === s.value
                ? "bg-indigo-600 text-white"
                : "border border-gray-200 bg-white text-gray-700 hover:bg-gray-50"
            )}
          >
            {s.label}
          </button>
        ))}
      </div>

      <div className="overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
        {isLoading ? (
          <div className="flex items-center justify-center gap-2 py-12">
            <Loader2 className="h-5 w-5 animate-spin text-indigo-500" />
            <span className="text-sm text-gray-400">लोड हो रहा है...</span>
          </div>
        ) : items.length === 0 ? (
          <div className="py-14 text-center">
            <Inbox className="mx-auto mb-3 h-8 w-8 text-gray-300" />
            <p className="text-sm text-gray-500">कोई संदेश नहीं / No messages here</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-50">
            {items.map((item) => (
              <InquiryRow
                key={item.id}
                item={item}
                open={openId === item.id}
                onToggle={() => setOpenId(openId === item.id ? null : item.id)}
                onChanged={() => queryClient.invalidateQueries({ queryKey: ["admin-inquiries"] })}
              />
            ))}
          </div>
        )}

        {(data?.totalPages ?? 0) > 1 && (
          <div className="flex items-center justify-between border-t border-gray-100 bg-gray-50/50 px-5 py-3 text-xs">
            <span className="text-gray-400">
              {data?.totalElements} संदेश · पृष्ठ {page + 1} / {data?.totalPages}
            </span>
            <div className="flex gap-2">
              <button
                onClick={() => setPage((p) => Math.max(0, p - 1))}
                disabled={page === 0}
                className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 font-medium text-gray-600 disabled:opacity-40"
              >
                पिछला
              </button>
              <button
                onClick={() => setPage((p) => p + 1)}
                disabled={page + 1 >= (data?.totalPages ?? 1)}
                className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 font-medium text-gray-600 disabled:opacity-40"
              >
                अगला
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function InquiryRow({
  item, open, onToggle, onChanged,
}: {
  item: Inquiry;
  open: boolean;
  onToggle: () => void;
  onChanged: () => void;
}) {
  const [note, setNote] = useState(item.adminNote ?? "");

  const save = useMutation({
    mutationFn: (status: InquiryStatus) =>
      inquiryAdminApi.setStatus(item.id, { status, adminNote: note.trim() || undefined }),
    onSuccess: () => { toast.success("अद्यतन / Updated"); onChanged(); },
    onError: () => toast.error("अद्यतन में त्रुटि / Could not update"),
  });

  // Structured extras some forms attach; shown as-is rather than guessed at.
  let details: Record<string, unknown> | null = null;
  if (item.detailsJson) {
    try { details = JSON.parse(item.detailsJson); } catch { details = null; }
  }

  return (
    <div className={cn("transition-colors", open ? "bg-indigo-50/30" : "hover:bg-gray-50")}>
      <button onClick={onToggle} className="flex w-full items-center gap-3 px-5 py-4 text-left">
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-2">
            <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[10px] font-medium text-gray-600">
              {TYPE_LABELS[item.type] ?? item.type}
            </span>
            <span className={cn("rounded-full px-2 py-0.5 text-[10px] font-medium", STATUS_STYLE[item.status])}>
              {item.status}
            </span>
            <span className="text-[11px] text-gray-400">{when(item.createdAt)}</span>
          </div>
          <p className="mt-1 truncate text-sm font-medium text-gray-900">
            {item.subject?.trim() || item.message.slice(0, 70)}
          </p>
          <p className="truncate text-xs text-gray-500">
            {item.name} · {item.email}
          </p>
        </div>
        <ChevronDown className={cn("h-4 w-4 shrink-0 text-gray-400 transition-transform", open && "rotate-180")} />
      </button>

      {open && (
        <div className="space-y-4 border-t border-gray-100 px-5 py-4">
          <p className="whitespace-pre-line text-sm leading-relaxed text-gray-700">{item.message}</p>

          {details && (
            <dl className="rounded-lg bg-gray-50 p-3 text-xs">
              {Object.entries(details).map(([k, v]) => (
                <div key={k} className="flex gap-2 py-0.5">
                  <dt className="font-medium text-gray-500">{k}</dt>
                  <dd className="text-gray-700">{String(v)}</dd>
                </div>
              ))}
            </dl>
          )}

          <a
            href={`mailto:${item.email}${item.subject ? `?subject=${encodeURIComponent("Re: " + item.subject)}` : ""}`}
            className="inline-flex items-center gap-1.5 text-xs font-medium text-indigo-600 hover:underline"
          >
            <Mail className="h-3.5 w-3.5" />
            {item.email} को उत्तर दें / Reply
          </a>

          <div>
            <label className="mb-1 block text-xs font-medium text-gray-500">
              टिप्पणी / Internal note
            </label>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={2}
              maxLength={5000}
              placeholder="इस संदेश पर की गई कार्रवाई..."
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
          </div>

          <div className="flex flex-wrap items-center gap-2">
            {(["NEW", "REVIEWED", "CLOSED"] as InquiryStatus[]).map((s) => (
              <button
                key={s}
                onClick={() => save.mutate(s)}
                disabled={save.isPending}
                className={cn(
                  "rounded-lg px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50",
                  item.status === s
                    ? "bg-indigo-600 text-white"
                    : "border border-gray-200 bg-white text-gray-600 hover:bg-gray-50"
                )}
              >
                {s}
              </button>
            ))}
            {save.isPending && <Loader2 className="h-4 w-4 animate-spin text-indigo-500" />}
          </div>
        </div>
      )}
    </div>
  );
}
