import { Form, redirect, useNavigate } from "react-router";
import { auth } from "~/lib/auth.server";
import type { Route } from "./+types/$teamId.settings";

import {
  findTeamById,
  updateTeam,
  removeTeamOwner,
} from "~/models/team";
import { findSeasonById } from "~/models/season";
import { Button } from "~/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
import { syncPrivateBracktParticipants } from "~/services/brackt.server";

export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
  return [{ title: `Team Settings — ${data?.team?.name ?? "Team"} - Brackt` }];
}

export async function loader(args: Route.LoaderArgs) {
  const { params } = args;
  const { teamId } = params;
  const session = await auth.api.getSession({ headers: args.request.headers });
  const userId = session?.user.id ?? null;

  if (!userId) {
    throw new Response("You must be logged in", { status: 401 });
  }

  const team = await findTeamById(teamId);

  if (!team) {
    throw new Response("Team not found", { status: 404 });
  }

  // Only the team owner can access settings
  if (team.ownerId !== userId) {
    throw new Response("You do not have access to this team", { status: 403 });
  }

  const season = await findSeasonById(team.seasonId);

  if (!season) {
    throw new Response("Season not found", { status: 404 });
  }

  return { team, season };
}

export async function action(args: Route.ActionArgs) {
  const { params, request } = args;
  const { teamId } = params;
  const session = await auth.api.getSession({ headers: args.request.headers });
  const userId = session?.user.id ?? null;

  if (!userId) {
    throw new Response("You must be logged in", { status: 401 });
  }

  const team = await findTeamById(teamId);

  if (!team) {
    throw new Response("Team not found", { status: 404 });
  }

  // Only the team owner can modify settings
  if (team.ownerId !== userId) {
    throw new Response("You do not have access to this team", { status: 403 });
  }

  const formData = await request.formData();
  const intent = formData.get("intent");

  if (intent === "update") {
    const name = formData.get("name");
    const logoUrl = formData.get("logoUrl");

    if (!name || typeof name !== "string") {
      return { error: "Team name is required" };
    }

    await updateTeam(teamId, {
      name: name.trim(),
      logoUrl: logoUrl && typeof logoUrl === "string" ? logoUrl.trim() : undefined,
    });
    await syncPrivateBracktParticipants(team.seasonId);

    const season = await findSeasonById(team.seasonId);
    return redirect(`/leagues/${season?.leagueId}?updated=true`);
  }

  if (intent === "leave") {
    await removeTeamOwner(teamId);
    return redirect("/?left=true");
  }

  return { error: "Invalid action" };
}

export default function TeamSettings({ loaderData }: Route.ComponentProps) {
  const { team, season } = loaderData;
  const navigate = useNavigate();

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="max-w-2xl mx-auto">
        <div className="mb-8">
          <div className="flex items-center justify-between mb-2">
            <h1 className="text-4xl font-bold">Team Settings</h1>
            <Button
              variant="outline"
              onClick={() => navigate(`/leagues/${season.leagueId}`)}
            >
              Back to League
            </Button>
          </div>
          <p className="text-muted-foreground">
            Manage your team settings and preferences
          </p>
        </div>

        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Team Information</CardTitle>
              <CardDescription>
                Update your team name and logo
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Form method="post" className="space-y-4">
                <input type="hidden" name="intent" value="update" />
                
                <div className="space-y-2">
                  <Label htmlFor="name">Team Name</Label>
                  <Input
                    id="name"
                    name="name"
                    type="text"
                    defaultValue={team.name}
                    required
                    maxLength={255}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="logoUrl">Team Logo URL (optional)</Label>
                  <Input
                    id="logoUrl"
                    name="logoUrl"
                    type="url"
                    defaultValue={team.logoUrl || ""}
                    placeholder="https://example.com/logo.png"
                    maxLength={512}
                  />
                  <p className="text-xs text-muted-foreground">
                    Enter a URL to an image for your team logo
                  </p>
                </div>

                <Button type="submit">Save Changes</Button>
              </Form>
            </CardContent>
          </Card>

          <Card className="border-destructive">
            <CardHeader>
              <CardTitle className="text-destructive">Danger Zone</CardTitle>
              <CardDescription>
                Irreversible actions for your team
              </CardDescription>
            </CardHeader>
            <CardContent>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="destructive">Leave League</Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This will remove you as the owner of "{team.name}" and make the team
                      available for others to claim. This action cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <Form method="post">
                      <input type="hidden" name="intent" value="leave" />
                      <AlertDialogAction type="submit" className="bg-destructive hover:bg-destructive/90">
                        Leave League
                      </AlertDialogAction>
                    </Form>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
