import { Form } from "react-router";
import type { Route } from "./+types/admin.standings-snapshots";

import { logger } from "~/lib/logger";
import { database } from "~/database/context";
import { eq, or } from "drizzle-orm";
import * as schema from "~/database/schema";
import { createDailySnapshot } from "~/models/standings";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import { Badge } from "~/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "~/components/ui/table";
import { Calendar, RefreshCw, CheckCircle2, AlertCircle } from "lucide-react";

export function meta(): Route.MetaDescriptors {
  return [{ title: "Standings Snapshots - Brackt Admin" }];
}

export async function loader() {
  const db = database();

  // Get all active and draft seasons
  const seasons = await db.query.seasons.findMany({
    where: or(
      eq(schema.seasons.status, "active"),
      eq(schema.seasons.status, "draft")
    ),
    with: {
      league: true,
    },
    orderBy: (s, { desc }) => [desc(s.createdAt)],
  });

  // For each season, get the most recent snapshot
  const seasonsWithSnapshots = await Promise.all(
    seasons.map(async (season) => {
      const mostRecentSnapshot = await db.query.teamStandingsSnapshots.findFirst({
        where: eq(schema.teamStandingsSnapshots.seasonId, season.id),
        orderBy: (snapshots, { desc }) => [desc(snapshots.snapshotDate)],
      });

      return {
        ...season,
        lastSnapshotDate: mostRecentSnapshot?.snapshotDate || null,
        lastSnapshotTime: mostRecentSnapshot?.createdAt || null,
      };
    })
  );

  return {
    seasons: seasonsWithSnapshots,
  };
}

export async function action({ request }: Route.ActionArgs) {
  const db = database();
  const formData = await request.formData();
  const intent = formData.get("intent");
  const seasonId = formData.get("seasonId") as string;

  try {
    if (intent === "create-snapshot") {
      if (seasonId === "all") {
        // Create snapshots for all active seasons
        const seasons = await db.query.seasons.findMany({
          where: or(
            eq(schema.seasons.status, "active"),
            eq(schema.seasons.status, "draft")
          ),
        });

        for (const season of seasons) {
          await createDailySnapshot(season.id, db);
        }

        return {
          success: true,
          message: `Created snapshots for ${seasons.length} season(s)`,
        };
      } else {
        // Create snapshot for specific season
        await createDailySnapshot(seasonId, db);
        return {
          success: true,
          message: "Snapshot created successfully",
        };
      }
    }

    return {
      success: false,
      message: "Invalid intent",
    };
  } catch (error) {
    logger.error("Error creating snapshot:", error);
    return {
      success: false,
      message: error instanceof Error ? error.message : "Unknown error",
    };
  }
}

export default function AdminStandingsSnapshots({
  loaderData,
  actionData,
}: Route.ComponentProps) {
  const { seasons } = loaderData;
  const today = new Date().toISOString().split("T")[0];

  return (
    <div className="p-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">Standings Snapshots</h1>
        <p className="text-muted-foreground">
          Manage daily standings snapshots for historical tracking and 7-day
          comparison
        </p>
      </div>

      {/* Action Result */}
      {actionData && (
        <Card
          className={`mb-6 ${
            actionData.success
              ? "border-emerald-500/30 bg-emerald-500/10"
              : "border-destructive/30 bg-destructive/10"
          }`}
        >
          <CardContent className="flex items-center gap-3 pt-6">
            {actionData.success ? (
              <CheckCircle2 className="h-5 w-5 text-emerald-400" />
            ) : (
              <AlertCircle className="h-5 w-5 text-destructive" />
            )}
            <p
              className={
                actionData.success ? "text-emerald-400" : "text-destructive"
              }
            >
              {actionData.message}
            </p>
          </CardContent>
        </Card>
      )}

      {/* Info Card */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            Snapshot System
          </CardTitle>
          <CardDescription>
            Snapshots are automatically created daily for all active seasons.
            Use the buttons below to manually trigger snapshot creation if
            needed.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3 text-sm">
            <p>
              <strong>Automatic Snapshots:</strong> The system creates snapshots
              once per day for all active seasons that don't already have a snapshot for today.
            </p>
            <p>
              <strong>Manual Snapshots:</strong> Use the "Create Snapshot"
              buttons below to manually trigger snapshot creation for specific
              seasons or all active seasons.
            </p>
            <p>
              <strong>7-Day Comparison:</strong> Standings pages show movement
              indicators comparing current rank to the snapshot from 7 days ago.
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Bulk Actions */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Bulk Actions</CardTitle>
          <CardDescription>
            Create snapshots for all active seasons at once
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Form method="post">
            <input type="hidden" name="intent" value="create-snapshot" />
            <input type="hidden" name="seasonId" value="all" />
            <Button type="submit" className="w-full sm:w-auto">
              <RefreshCw className="h-4 w-4 mr-2" />
              Create Snapshots for All Active Seasons
            </Button>
          </Form>
        </CardContent>
      </Card>

      {/* Seasons Table */}
      <Card>
        <CardHeader>
          <CardTitle>Active Seasons</CardTitle>
          <CardDescription>
            {seasons.length} season(s) eligible for snapshots
          </CardDescription>
        </CardHeader>
        <CardContent>
          {seasons.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <p>No active or draft seasons found</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>League</TableHead>
                  <TableHead>Season</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Last Snapshot</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {seasons.map((season) => {
                  const hasSnapshotToday =
                    season.lastSnapshotDate === today;
                  return (
                    <TableRow key={season.id}>
                      <TableCell className="font-medium">
                        {season.league.name}
                      </TableCell>
                      <TableCell>{season.year}</TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            season.status === "active"
                              ? "default"
                              : "secondary"
                          }
                        >
                          {season.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {season.lastSnapshotDate ? (
                          <div className="flex items-center gap-2">
                            <span className="text-sm">
                              {season.lastSnapshotDate}
                            </span>
                            {hasSnapshotToday && (
                              <Badge
                                variant="outline"
                                className="text-xs bg-emerald-500/15 text-emerald-400 border-emerald-500/30"
                              >
                                Today
                              </Badge>
                            )}
                          </div>
                        ) : (
                          <span className="text-muted-foreground text-sm">
                            No snapshots yet
                          </span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Form method="post" className="inline">
                          <input
                            type="hidden"
                            name="intent"
                            value="create-snapshot"
                          />
                          <input
                            type="hidden"
                            name="seasonId"
                            value={season.id}
                          />
                          <Button
                            type="submit"
                            variant="outline"
                            size="sm"
                            disabled={hasSnapshotToday}
                          >
                            <RefreshCw className="h-3 w-3 mr-1" />
                            {hasSnapshotToday
                              ? "Already Created"
                              : "Create Snapshot"}
                          </Button>
                        </Form>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
