"use client";

import { useEffect, useMemo, useState } from "react";

import { Download } from "lucide-react";
import { Bar, BarChart, CartesianGrid, Cell, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useCruiseData } from "@/hooks/use-cruise-data";
import {
  exportToCsv,
  getBookings,
  getDashboardStats,
  getGuests,
  getPayments,
  getReferrals,
  getSailingById,
} from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";

const CHART_COLORS = ["#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444"];

export default function ReportsPage() {
  const [chartsReady, setChartsReady] = useState(false);
  const { data: bookings, ready: bookingsReady } = useCruiseData(getBookings);
  const { data: payments, ready: paymentsReady } = useCruiseData(getPayments);

  useEffect(() => {
    setChartsReady(true);
  }, []);

  const stats = useMemo(() => getDashboardStats(), [bookings, payments]);

  const revenueBySailing = useMemo(() => {
    const map = new Map<string, number>();
    for (const p of payments.filter((pay) => pay.status === "paid")) {
      const booking = bookings.find((b) => b.id === p.bookingId);
      if (!booking) continue;
      const name = getSailingById(booking.sailingId)?.name ?? "Unknown";
      map.set(name, (map.get(name) ?? 0) + p.amount);
    }
    return [...map.entries()].map(([name, revenue]) => ({ name, revenue }));
  }, [bookings, payments]);

  const bookingsByStatus = useMemo(() => {
    const counts: Record<string, number> = {};
    for (const b of bookings) {
      counts[b.status] = (counts[b.status] ?? 0) + 1;
    }
    return Object.entries(counts).map(([status, count]) => ({ status, count }));
  }, [bookings]);

  const monthlyRevenue = useMemo(() => {
    const map = new Map<string, number>();
    for (const p of payments.filter((pay) => pay.status === "paid" && pay.paidAt)) {
      const month = p.paidAt!.slice(0, 7);
      map.set(month, (map.get(month) ?? 0) + p.amount);
    }
    return [...map.entries()]
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([month, revenue]) => ({ month, revenue }));
  }, [payments]);

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h1 className="font-semibold text-xl">Reports</h1>
          <p className="text-muted-foreground text-sm">Revenue, bookings, and export tools</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              exportToCsv(
                bookings.map((b) => ({
                  code: b.bookingCode,
                  sailing: getSailingById(b.sailingId)?.name,
                  total: b.total,
                  status: b.status,
                  created: b.createdAt,
                })),
                "bookings-export.csv",
              )
            }
          >
            <Download className="size-4" />
            Export Bookings
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              exportToCsv(
                payments.map((p) => ({
                  label: p.label,
                  amount: p.amount,
                  status: p.status,
                  dueDate: p.dueDate,
                  paidAt: p.paidAt ?? "",
                })),
                "payments-export.csv",
              )
            }
          >
            <Download className="size-4" />
            Export Payments
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              exportToCsv(
                getGuests().map((g) => ({
                  name: g.name,
                  email: g.email,
                  phone: g.phone,
                  created: g.createdAt,
                })),
                "guests-export.csv",
              )
            }
          >
            <Download className="size-4" />
            Export Guests
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              exportToCsv(
                getReferrals().map((r) => ({
                  code: r.code,
                  partner: r.affiliateName,
                  commission: r.commissionPercent,
                  earned: r.earnedAmount ?? 0,
                  bookingId: r.bookingId ?? "",
                })),
                "referrals-export.csv",
              )
            }
          >
            <Download className="size-4" />
            Export Referrals
          </Button>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[
          { label: "Total bookings", value: stats.totalBookings },
          { label: "Revenue collected", value: formatCurrency(stats.totalRevenue) },
          { label: "Outstanding balance", value: formatCurrency(stats.outstanding) },
          { label: "Cabin occupancy", value: `${stats.occupancy}%` },
        ].map(({ label, value }) => (
          <Card key={label}>
            <CardHeader className="pb-2">
              <CardDescription>{label}</CardDescription>
              <CardTitle className="text-2xl">{value}</CardTitle>
            </CardHeader>
          </Card>
        ))}
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Revenue by sailing</CardTitle>
          </CardHeader>
          <CardContent className="h-72">
            {chartsReady && bookingsReady && paymentsReady ? (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={revenueBySailing}>
                  <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                  <XAxis dataKey="name" tick={{ fontSize: 11 }} interval={0} angle={-20} textAnchor="end" height={60} />
                  <YAxis tickFormatter={(v) => `$${v / 1000}k`} />
                  <Tooltip formatter={(v) => formatCurrency(Number(v))} />
                  <Bar dataKey="revenue" fill="#6366f1" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex h-full items-center justify-center text-muted-foreground text-sm">Loading chart…</div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Bookings by status</CardTitle>
          </CardHeader>
          <CardContent className="h-72">
            {chartsReady && bookingsReady && paymentsReady ? (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={bookingsByStatus} dataKey="count" nameKey="status" cx="50%" cy="50%" outerRadius={90} label>
                    {bookingsByStatus.map((_, i) => (
                      <Cell key={_.status} fill={CHART_COLORS[i % CHART_COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex h-full items-center justify-center text-muted-foreground text-sm">Loading chart…</div>
            )}
          </CardContent>
        </Card>

        {monthlyRevenue.length > 0 && (
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle className="text-base">Monthly revenue</CardTitle>
            </CardHeader>
            <CardContent className="h-72">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={monthlyRevenue}>
                  <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                  <XAxis dataKey="month" />
                  <YAxis tickFormatter={(v) => `$${v / 1000}k`} />
                  <Tooltip formatter={(v) => formatCurrency(Number(v))} />
                  <Bar dataKey="revenue" fill="#0ea5e9" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
