"use client";

import { useEffect, useRef, useState } from "react";
import {
  MapPin, Users, Calendar, Wrench, MessageSquare, Eye, Trash2,
  MailOpen, MailCheck, Building2, Mail, AlertCircle, Globe,
  ShieldCheck, Plane, ClipboardList, ChevronLeft, ChevronRight, Download,
  MoreHorizontal,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
} from "@/components/ui/pagination";
import { DataTable, type Column } from "@/components/admin/DataTable";
import { FormSheet } from "@/components/admin/FormSheet";
import { PageHeader } from "@/components/admin/PageHeader";
import { toast } from "sonner";
import {
  type QuoteRequest,
  getQuotations,
  updateQuotationReadStatus,
  deleteQuotation,
} from "@/services/quotations";

// ─── Helpers ───────────────────────────────────────────────────────────────────

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}

function formatDateTime(iso: string) {
  return new Date(iso).toLocaleString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

// ─── Detail field helper ───────────────────────────────────────────────────────

function DetailField({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ElementType;
  label: string;
  value: string;
}) {
  return (
    <div className="flex items-start gap-3">
      <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted">
        <Icon className="h-3.5 w-3.5 text-muted-foreground" />
      </div>
      <div className="min-w-0">
        <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold">
          {label}
        </p>
        <p className="text-sm text-foreground mt-0.5 break-words leading-relaxed">{value}</p>
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function QuotesAdminPage() {
  const [quotes, setQuotes] = useState<QuoteRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [viewing, setViewing] = useState<QuoteRequest | null>(null);
  const [downloading, setDownloading] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const fetchQuotes = (q: string, p: number) => {
    setLoading(true);
    getQuotations(q || undefined, p)
      .then((res) => {
        setQuotes(res.data);
        setLastPage(res.meta.last_page);
        setTotal(res.meta.total);
      })
      .catch(() => toast.error("Failed to load quote requests."))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchQuotes("", 1);
  }, []);

  const handleSearchChange = (value: string) => {
    setSearch(value);
    setPage(1);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => fetchQuotes(value, 1), 400);
  };

  const handlePageChange = (p: number) => {
    setPage(p);
    fetchQuotes(search, p);
  };

  const unreadCount = quotes.filter((q) => !q.is_read).length;

  const handleView = async (item: QuoteRequest) => {
    setViewing(item);
    if (!item.is_read) {
      try {
        await updateQuotationReadStatus(item.id, true);
        setQuotes((prev) =>
          prev.map((q) => (q.id === item.id ? { ...q, is_read: true } : q))
        );
        setViewing((prev) => (prev?.id === item.id ? { ...prev, is_read: true } : prev));
      } catch {
        // API error already toasted by interceptor
      }
    }
  };

  const handleToggleRead = async (item: QuoteRequest) => {
    const newValue = !item.is_read;
    try {
      await updateQuotationReadStatus(item.id, newValue);
      setQuotes((prev) =>
        prev.map((q) => (q.id === item.id ? { ...q, is_read: newValue } : q))
      );
      if (viewing?.id === item.id) {
        setViewing((prev) => (prev ? { ...prev, is_read: newValue } : prev));
      }
      toast.success(newValue ? "Marked as read." : "Marked as unread.");
    } catch {
      // API error already toasted by interceptor
    }
  };

  const handleDownloadPDF = async (item: QuoteRequest) => {
    setDownloading(true);
    try {
      const [{ pdf }, { QuotePDF }] = await Promise.all([
        import("@react-pdf/renderer"),
        import("@/components/admin/QuotePDF"),
      ]);
      const logoUrl = `${window.location.origin}/logo-white.png`;
      const blob = await pdf(
        <QuotePDF quote={item} logoUrl={logoUrl} />
      ).toBlob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      const year = new Date(item.created_at).getFullYear();
      a.href = url;
      a.download = `PBG-QR-${year}-${String(item.id).padStart(4, "0")}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      toast.error("Failed to generate PDF.");
    } finally {
      setDownloading(false);
    }
  };

  const handleDelete = async (item: QuoteRequest) => {
    setQuotes((prev) => prev.filter((q) => q.id !== item.id));
    if (viewing?.id === item.id) setViewing(null);
    try {
      await deleteQuotation(item.id);
      toast.success("Quote request deleted.");
    } catch {
      setQuotes((prev) => [item, ...prev]);
    }
  };

  const columns: Column<QuoteRequest>[] = [
    {
      key: "first_name",
      label: "Requester",
      render: (item) => (
        <div className="flex items-center gap-2.5 min-w-0">
          {!item.is_read && (
            <span className="h-2 w-2 shrink-0 rounded-full bg-blue-500" />
          )}
          <div className="min-w-0">
            <p
              className={`truncate ${
                !item.is_read
                  ? "font-semibold text-foreground"
                  : "font-medium text-foreground"
              }`}
            >
              {item.first_name} {item.last_name}
            </p>
            <p className="text-xs text-muted-foreground truncate">{item.email}</p>
          </div>
        </div>
      ),
    },
    {
      key: "company_name",
      label: "Company",
      render: (item) => (
        <span className="text-sm text-foreground">{item.company_name}</span>
      ),
    },
    {
      key: "service",
      label: "Service",
      render: (item) => (
        <Badge variant="secondary" className="text-xs font-normal whitespace-nowrap">
          {item.service?.title ?? "Others"}
        </Badge>
      ),
    },
    {
      key: "project_location",
      label: "Location",
      render: (item) => (
        <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
          <MapPin className="h-3.5 w-3.5 shrink-0" />
          <span className="truncate max-w-[160px]">{item.project_location}</span>
        </div>
      ),
    },
    {
      key: "delivery_deadline",
      label: "Deadline",
      render: (item) =>
        item.delivery_deadline ? (
          <span className="text-xs text-muted-foreground whitespace-nowrap">
            {formatDate(item.delivery_deadline)}
          </span>
        ) : (
          <span className="text-xs text-muted-foreground">—</span>
        ),
      className: "w-28",
    },
    {
      key: "created_at",
      label: "Received",
      render: (item) => (
        <span className="text-xs text-muted-foreground whitespace-nowrap">
          {formatDate(item.created_at)}
        </span>
      ),
      className: "w-28",
    },
    {
      key: "actions_inline",
      label: "",
      render: (item) => (
        <DropdownMenu>
          <DropdownMenuTrigger
            className="inline-flex h-8 w-8 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100 hover:bg-accent hover:text-accent-foreground focus-visible:outline-none"
            onClick={(e) => e.stopPropagation()}
          >
            <MoreHorizontal className="h-4 w-4" />
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => handleView(item)}>
              <Eye className="mr-2 h-3.5 w-3.5" /> View
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => handleToggleRead(item)}>
              {item.is_read
                ? <><MailOpen className="mr-2 h-3.5 w-3.5" /> Mark as Unread</>
                : <><MailCheck className="mr-2 h-3.5 w-3.5" /> Mark as Read</>}
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => handleDownloadPDF(item)}>
              <Download className="mr-2 h-3.5 w-3.5" /> PDF
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              className="text-destructive focus:text-destructive"
              onClick={() => handleDelete(item)}
            >
              <Trash2 className="mr-2 h-3.5 w-3.5" /> Delete
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      className: "w-12",
    },
  ];

  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
      <PageHeader
        title="Quote Requests"
        description="Project quotation requests submitted through the website."
      >
        {unreadCount > 0 && (
          <Badge variant="default" className="gap-1.5">
            <span className="h-1.5 w-1.5 rounded-full bg-white/80" />
            {unreadCount} unread
          </Badge>
        )}
      </PageHeader>

      <DataTable
        data={quotes}
        columns={columns}
        searchValue={search}
        onSearchChange={handleSearchChange}
        searchPlaceholder="Search by company…"
        loading={loading}
      />

      {lastPage > 1 && (
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>{total} request{total !== 1 ? "s" : ""}</span>
          <Pagination className="mx-0 w-auto justify-end">
            <PaginationContent>
              <PaginationItem>
                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(page - 1)}
                  disabled={page <= 1 || loading}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
              </PaginationItem>
              <PaginationItem>
                <span className="px-3 text-sm">
                  Page {page} of {lastPage}
                </span>
              </PaginationItem>
              <PaginationItem>
                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(page + 1)}
                  disabled={page >= lastPage || loading}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      )}

      {/* Detail sheet */}
      <FormSheet
        open={!!viewing}
        onOpenChange={(open) => {
          if (!open) setViewing(null);
        }}
        title="Quote Request Details"
        description={
          viewing ? `Received ${formatDateTime(viewing.created_at)}` : undefined
        }
        footer={
          viewing ? (
            <div className="flex w-full items-center justify-between">
              <Button
                variant="outline"
                size="sm"
                className="gap-2"
                onClick={() => handleDownloadPDF(viewing)}
                disabled={downloading}
              >
                <Download className="h-3.5 w-3.5" />
                {downloading ? "Generating…" : "PDF"}
              </Button>

              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  className="gap-2"
                  onClick={() => handleToggleRead(viewing)}
                >
                  {viewing.is_read ? (
                    <><MailOpen className="h-3.5 w-3.5" /> Mark as Unread</>
                  ) : (
                    <><MailCheck className="h-3.5 w-3.5" /> Mark as Read</>
                  )}
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="gap-2 text-destructive border-destructive/30 hover:bg-destructive/5 hover:text-destructive"
                  onClick={() => handleDelete(viewing)}
                  title="Delete"
                >
                  <Trash2 className="h-3.5 w-3.5" /> Delete
                </Button>
              </div>
            </div>
          ) : undefined
        }
      >
        {viewing && (
          <div className="space-y-5">
            {/* Contact info */}
            <div className="space-y-3.5">
              <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold">
                Contact Information
              </p>
              <DetailField
                icon={Mail}
                label="Full Name"
                value={`${viewing.first_name} ${viewing.last_name}`}
              />
              <DetailField icon={Mail} label="Email" value={viewing.email} />
              <DetailField icon={Building2} label="Company" value={viewing.company_name} />
              {viewing.service && (
                <DetailField icon={Wrench} label="Service Required" value={viewing.service.title} />
              )}
            </div>

            <Separator />

            {/* Project details */}
            <div className="space-y-3.5">
              <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold">
                Project Details
              </p>
              <DetailField icon={MapPin} label="Project Location" value={viewing.project_location} />
              {viewing.delivery_deadline && (
                <DetailField
                  icon={Calendar}
                  label="Delivery Deadline"
                  value={formatDate(viewing.delivery_deadline)}
                />
              )}
              {viewing.personnel_required != null && (
                <DetailField
                  icon={Users}
                  label="Personnel Required"
                  value={String(viewing.personnel_required)}
                />
              )}
              {viewing.scope_of_work && (
                <DetailField
                  icon={ClipboardList}
                  label="Scope of Work"
                  value={viewing.scope_of_work}
                />
              )}
              {viewing.primary_concerns && (
                <DetailField
                  icon={AlertCircle}
                  label="Primary Concerns"
                  value={viewing.primary_concerns}
                />
              )}
              {viewing.previous_inspections && (
                <DetailField
                  icon={MessageSquare}
                  label="Previous Inspections"
                  value={viewing.previous_inspections}
                />
              )}
            </div>

            <Separator />

            {/* Logistics */}
            <div className="space-y-3.5">
              <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold">
                Logistics
              </p>
              {viewing.site_accessibility && (
                <DetailField
                  icon={Globe}
                  label="Site Accessibility"
                  value={viewing.site_accessibility}
                />
              )}
              {viewing.permits_required && (
                <DetailField
                  icon={ShieldCheck}
                  label="Permits Required"
                  value={viewing.permits_required}
                />
              )}
              {viewing.visas_required && (
                <DetailField
                  icon={Plane}
                  label="Visas Required"
                  value={viewing.visas_required}
                />
              )}
              {viewing.travel_provided && (
                <DetailField
                  icon={Plane}
                  label="Travel & Accommodation"
                  value={viewing.travel_provided}
                />
              )}
            </div>


          </div>
        )}
      </FormSheet>
    </div>
  );
}
