import { useQuery } from "@tanstack/react-query";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  Legend,
} from "recharts";
import { supabase } from "@/integrations/supabase/client";

const MONTHS = 6;

function monthKeys() {
  const now = new Date();
  return Array.from({ length: MONTHS }, (_, i) => {
    const d = new Date(now.getFullYear(), now.getMonth() - (MONTHS - 1 - i), 1);
    return { key: `${d.getFullYear()}-${d.getMonth()}`, label: d.toLocaleString("en", { month: "short" }) };
  });
}

const bucket = (iso: string) => {
  const d = new Date(iso);
  return `${d.getFullYear()}-${d.getMonth()}`;
};

function ChartCard({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
  return (
    <section className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
      <h2 className="text-sm font-semibold">{title}</h2>
      <p className="text-[11px] text-muted-foreground">{subtitle}</p>
      <div className="mt-3 h-56 w-full">
        <ResponsiveContainer width="100%" height="100%">
          {children as React.ReactElement}
        </ResponsiveContainer>
      </div>
    </section>
  );
}

export function AnalyticsPanel() {
  const { data, isLoading } = useQuery({
    queryKey: ["admin-analytics"],
    queryFn: async () => {
      const [bookings, scans, reviews] = await Promise.all([
        supabase.from("bookings").select("created_at,status"),
        supabase.from("mold_scans").select("created_at"),
        supabase.from("reviews").select("created_at,rating,approved"),
      ]);
      if (bookings.error) throw bookings.error;
      if (scans.error) throw scans.error;
      if (reviews.error) throw reviews.error;
      return { bookings: bookings.data, scans: scans.data, reviews: reviews.data };
    },
  });

  if (isLoading || !data) return <p className="mt-4 text-sm text-muted-foreground">Loading analytics…</p>;

  const rows = monthKeys().map(({ key, label }) => {
    const bookings = data.bookings.filter((b) => bucket(b.created_at) === key);
    const scans = data.scans.filter((s) => bucket(s.created_at) === key).length;
    const inspections = bookings.filter((b) =>
      ["inspector_assigned", "inspection_completed", "treatment_scheduled", "completed"].includes(b.status),
    ).length;
    const monthReviews = data.reviews.filter((r) => bucket(r.created_at) === key);
    const avgRating = monthReviews.length
      ? Number((monthReviews.reduce((sum, r) => sum + r.rating, 0) / monthReviews.length).toFixed(2))
      : 0;
    return {
      month: label,
      bookings: bookings.length,
      scans,
      inspections,
      conversion: scans ? Math.round((bookings.length / scans) * 100) : 0,
      reviews: monthReviews.length,
      approved: monthReviews.filter((r) => r.approved).length,
      avgRating,
    };
  });

  const axis = { stroke: "currentColor", fontSize: 11 };

  return (
    <div className="mt-4 space-y-4 text-muted-foreground">
      <ChartCard title="Booking volume & AI scan usage" subtitle="Last 6 months">
        <BarChart data={rows}>
          <CartesianGrid strokeDasharray="3 3" opacity={0.2} />
          <XAxis dataKey="month" {...axis} />
          <YAxis allowDecimals={false} {...axis} />
          <Tooltip />
          <Legend wrapperStyle={{ fontSize: 11 }} />
          <Bar dataKey="bookings" name="Bookings" fill="hsl(var(--chart-1, 152 45% 40%))" radius={[4, 4, 0, 0]} />
          <Bar dataKey="scans" name="AI scans" fill="hsl(var(--chart-2, 205 70% 50%))" radius={[4, 4, 0, 0]} />
        </BarChart>
      </ChartCard>

      <ChartCard title="Conversion to inspections" subtitle="Scans that turned into bookings, and bookings reaching inspection">
        <LineChart data={rows}>
          <CartesianGrid strokeDasharray="3 3" opacity={0.2} />
          <XAxis dataKey="month" {...axis} />
          <YAxis allowDecimals={false} {...axis} />
          <Tooltip />
          <Legend wrapperStyle={{ fontSize: 11 }} />
          <Line type="monotone" dataKey="conversion" name="Scan → booking %" stroke="hsl(var(--chart-1, 152 45% 40%))" strokeWidth={2} />
          <Line type="monotone" dataKey="inspections" name="Inspections" stroke="hsl(var(--chart-2, 205 70% 50%))" strokeWidth={2} />
        </LineChart>
      </ChartCard>

      <ChartCard title="Review trends" subtitle="Volume, approvals and average rating">
        <LineChart data={rows}>
          <CartesianGrid strokeDasharray="3 3" opacity={0.2} />
          <XAxis dataKey="month" {...axis} />
          <YAxis allowDecimals={false} {...axis} />
          <Tooltip />
          <Legend wrapperStyle={{ fontSize: 11 }} />
          <Line type="monotone" dataKey="reviews" name="Reviews" stroke="hsl(var(--chart-1, 152 45% 40%))" strokeWidth={2} />
          <Line type="monotone" dataKey="approved" name="Approved" stroke="hsl(var(--chart-2, 205 70% 50%))" strokeWidth={2} />
          <Line type="monotone" dataKey="avgRating" name="Avg rating" stroke="hsl(var(--chart-3, 42 90% 55%))" strokeWidth={2} />
        </LineChart>
      </ChartCard>
    </div>
  );
}