import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { AppShell } from "@/components/AppShell";
import { PaymentsAdmin } from "@/components/admin/PaymentsAdmin";
import { ReportsAdmin } from "@/components/admin/ReportsAdmin";
import { AnalyticsPanel } from "@/components/admin/AnalyticsPanel";
import { SettingsPanel } from "@/components/admin/SettingsPanel";
import { CompaniesAdmin } from "@/components/admin/CompaniesAdmin";
import { AuditLogs } from "@/components/admin/AuditLogs";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/use-auth";
import type { Database } from "@/integrations/supabase/types";

type BookingStatus = Database["public"]["Enums"]["booking_status"];

const statuses: BookingStatus[] = [
  "requested",
  "confirmed",
  "inspector_assigned",
  "inspection_completed",
  "treatment_scheduled",
  "completed",
  "cancelled",
];

export const Route = createFileRoute("/_authenticated/admin")({
  head: () => ({
    meta: [
      { title: "Admin dashboard | Emma Mold Inspection Services" },
      { name: "description", content: "Manage bookings, inspectors, quotations, reports and reviews." },
      { property: "og:title", content: "Admin dashboard" },
      { property: "og:description", content: "Operations dashboard for Emma Mold Inspection Services." },
    ],
  }),
  component: AdminPage,
});

const tabs = [
  "Overview",
  "Analytics",
  "Bookings",
  "Companies",
  "Payments",
  "Reports",
  "Reviews",
  "Audit logs",
  "Settings",
] as const;
type Tab = (typeof tabs)[number];

function AdminPage() {
  const { isAdmin, loading } = useAuth();
  const qc = useQueryClient();
  const [tab, setTab] = useState<Tab>("Overview");

  const bookings = useQuery({
    queryKey: ["admin-bookings"],
    enabled: isAdmin,
    queryFn: async () => {
      const { data, error } = await supabase.from("bookings").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data;
    },
  });

  const reviews = useQuery({
    queryKey: ["admin-reviews"],
    enabled: isAdmin,
    queryFn: async () => {
      const { data, error } = await supabase.from("reviews").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data;
    },
  });

  const reports = useQuery({
    queryKey: ["admin-reports"],
    enabled: isAdmin,
    queryFn: async () => {
      const { data, error } = await supabase.from("inspection_reports").select("id,reference,published");
      if (error) throw error;
      return data;
    },
  });

  if (loading) return <AppShell>Loading…</AppShell>;
  if (!isAdmin)
    return (
      <AppShell>
        <h1 className="text-2xl font-bold">Admin only</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          This area is restricted to the Emma Mold operations team.
        </p>
        <Link to="/dashboard" className="mt-4 inline-block text-sm font-semibold text-primary">
          Back to my account
        </Link>
      </AppShell>
    );

  const all = bookings.data ?? [];
  const stats = [
    { label: "Bookings", value: all.length },
    { label: "Pending", value: all.filter((b) => !["completed", "cancelled"].includes(b.status)).length },
    { label: "Completed", value: all.filter((b) => b.status === "completed").length },
    { label: "Reports", value: reports.data?.length ?? 0 },
  ];

  async function updateBooking(
    id: string,
    patch: { status?: BookingStatus; inspector_name?: string },
  ) {
    const { error } = await supabase.from("bookings").update(patch).eq("id", id);
    if (error) return toast.error("Update failed.");
    toast.success("Booking updated.");
    qc.invalidateQueries({ queryKey: ["admin-bookings"] });
  }

  async function setApproval(id: string, approved: boolean) {
    const { error } = await supabase.from("reviews").update({ approved }).eq("id", id);
    if (error) return toast.error("Update failed.");
    qc.invalidateQueries({ queryKey: ["admin-reviews"] });
  }

  return (
    <AppShell>
      <h1 className="text-2xl font-bold">Emma Exclusive Teams — Admin</h1>
      <p className="mt-1 text-sm text-muted-foreground">
        Full platform control: customers, companies, scans, bookings, payments and settings.
      </p>

      <div className="mt-4 flex flex-wrap gap-2">
        {tabs.map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`rounded-full px-4 py-2 text-xs font-semibold ${
              tab === t ? "bg-brand text-primary-foreground" : "bg-muted text-muted-foreground"
            }`}
          >
            {t}
          </button>
        ))}
      </div>

      {tab === "Overview" ? (
        <div className="mt-4 grid grid-cols-2 gap-3">
          {stats.map((s) => (
            <div key={s.label} className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
              <p className="text-2xl font-bold">{s.value}</p>
              <p className="text-xs text-muted-foreground">{s.label}</p>
            </div>
          ))}
        </div>
      ) : null}

      {tab === "Analytics" ? <AnalyticsPanel /> : null}
      {tab === "Payments" ? <PaymentsAdmin /> : null}
      {tab === "Reports" ? <ReportsAdmin /> : null}
      {tab === "Companies" ? <CompaniesAdmin /> : null}
      {tab === "Audit logs" ? <AuditLogs /> : null}
      {tab === "Settings" ? <SettingsPanel /> : null}

      {tab === "Bookings" ? (
        <div className="mt-4 space-y-3">
          {all.map((b) => (
            <article key={b.id} className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
              <h2 className="text-sm font-semibold">
                {b.service_name} — {b.full_name}
              </h2>
              <p className="mt-1 text-xs text-muted-foreground">
                {b.phone} • {b.email} • {b.address}
              </p>
              <p className="mt-1 text-xs text-muted-foreground">
                {b.preferred_date ?? "No date"} • {b.preferred_time} • {b.property_type} • {b.rooms} rooms
              </p>
              {b.notes ? <p className="mt-1 text-xs text-muted-foreground">Notes: {b.notes}</p> : null}
              <div className="mt-3 grid gap-2 sm:grid-cols-2">
                <select
                  className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
                  value={b.status}
                  onChange={(e) => updateBooking(b.id, { status: e.target.value as BookingStatus })}
                >
                  {statuses.map((s) => (
                    <option key={s} value={s}>
                      {s.replaceAll("_", " ")}
                    </option>
                  ))}
                </select>
                <input
                  className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
                  placeholder="Assign inspector"
                  defaultValue={b.inspector_name ?? ""}
                  onBlur={(e) =>
                    e.target.value !== (b.inspector_name ?? "") &&
                    updateBooking(b.id, { inspector_name: e.target.value })
                  }
                />
              </div>
            </article>
          ))}
          {all.length === 0 ? <p className="text-sm text-muted-foreground">No bookings yet.</p> : null}
        </div>
      ) : null}

      {tab === "Reviews" ? (
        <div className="mt-4 space-y-3">
          {reviews.data?.map((r) => (
            <article key={r.id} className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
              <h2 className="text-sm font-semibold">
                {r.author_name} — {r.rating}★
              </h2>
              <p className="mt-1 text-xs text-muted-foreground">{r.comment}</p>
              <button
                onClick={() => setApproval(r.id, !r.approved)}
                className="mt-3 rounded-xl bg-brand px-4 py-2 text-xs font-semibold text-primary-foreground"
              >
                {r.approved ? "Unpublish" : "Approve & publish"}
              </button>
            </article>
          ))}
          {!reviews.data?.length ? <p className="text-sm text-muted-foreground">No reviews yet.</p> : null}
        </div>
      ) : null}
    </AppShell>
  );
}