"use client";

import {
  useCallback,
  useEffect,
  useState,
  type ChangeEvent,
  type KeyboardEvent,
  type ReactElement,
  type SyntheticEvent,
} from "react";
import Link from "next/link";
import { Plus, Trash2, Users } from "lucide-react";
import { WorkspaceMemberRole } from "@mosaic/shared";
import { SettingsAccessDenied } from "@/components/settings/SettingsAccessDenied";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  createTeam,
  deleteTeam,
  fetchTeams,
  updateTeam,
  type CreateTeamDto,
  type TeamRecord,
  type UpdateTeamDto,
} from "@/lib/api/teams";
import { fetchUserWorkspaces } from "@/lib/api/workspaces";

const INITIAL_CREATE_FORM = {
  name: "",
  description: "",
};

const INITIAL_DETAIL_FORM = {
  name: "",
  description: "",
};

interface DetailInitialState {
  name: string;
  description: string;
}

function toMemberLabel(count: number): string {
  return `${String(count)} member${count === 1 ? "" : "s"}`;
}

export default function TeamsSettingsPage(): ReactElement {
  const [teams, setTeams] = useState<TeamRecord[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isRefreshing, setIsRefreshing] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [isAdmin, setIsAdmin] = useState<boolean | null>(null);

  const [isCreateOpen, setIsCreateOpen] = useState<boolean>(false);
  const [createForm, setCreateForm] = useState(INITIAL_CREATE_FORM);
  const [createError, setCreateError] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState<boolean>(false);

  const [detailTarget, setDetailTarget] = useState<TeamRecord | null>(null);
  const [detailForm, setDetailForm] = useState(INITIAL_DETAIL_FORM);
  const [detailInitial, setDetailInitial] = useState<DetailInitialState | null>(null);
  const [detailError, setDetailError] = useState<string | null>(null);
  const [isSavingDetails, setIsSavingDetails] = useState<boolean>(false);

  const [deleteTarget, setDeleteTarget] = useState<TeamRecord | null>(null);
  const [isDeleting, setIsDeleting] = useState<boolean>(false);

  const loadTeams = useCallback(async (showLoadingState: boolean): Promise<void> => {
    try {
      if (showLoadingState) {
        setIsLoading(true);
      } else {
        setIsRefreshing(true);
      }

      const data = await fetchTeams();
      setTeams(data);
      setError(null);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to load teams");
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchUserWorkspaces()
      .then((workspaces) => {
        const adminRoles: WorkspaceMemberRole[] = [
          WorkspaceMemberRole.OWNER,
          WorkspaceMemberRole.ADMIN,
        ];

        setIsAdmin(workspaces.some((workspace) => adminRoles.includes(workspace.role)));
      })
      .catch(() => {
        setIsAdmin(true); // fail open
      });
  }, []);

  useEffect(() => {
    if (isAdmin !== true) {
      return;
    }

    void loadTeams(true);
  }, [isAdmin, loadTeams]);

  function resetCreateForm(): void {
    setCreateForm(INITIAL_CREATE_FORM);
    setCreateError(null);
  }

  function openTeamDetails(team: TeamRecord): void {
    const nextDetailForm = {
      name: team.name,
      description: team.description ?? "",
    };

    setDetailTarget(team);
    setDetailForm(nextDetailForm);
    setDetailInitial({
      name: nextDetailForm.name,
      description: nextDetailForm.description,
    });
    setDetailError(null);
  }

  function resetTeamDetails(): void {
    setDetailTarget(null);
    setDetailForm(INITIAL_DETAIL_FORM);
    setDetailInitial(null);
    setDetailError(null);
  }

  function handleTeamRowKeyDown(event: KeyboardEvent<HTMLDivElement>, team: TeamRecord): void {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      openTeamDetails(team);
    }
  }

  async function handleCreateSubmit(event: SyntheticEvent): Promise<void> {
    event.preventDefault();
    setCreateError(null);

    const name = createForm.name.trim();
    if (!name) {
      setCreateError("Name is required.");
      return;
    }

    const description = createForm.description.trim();
    const dto: CreateTeamDto = { name };
    if (description) {
      dto.description = description;
    }

    try {
      setIsCreating(true);
      await createTeam(dto);
      setIsCreateOpen(false);
      resetCreateForm();
      await loadTeams(false);
    } catch (err: unknown) {
      setCreateError(err instanceof Error ? err.message : "Failed to create team");
    } finally {
      setIsCreating(false);
    }
  }

  async function handleDetailSubmit(event: SyntheticEvent): Promise<void> {
    event.preventDefault();

    if (detailTarget === null || detailInitial === null) {
      return;
    }

    const name = detailForm.name.trim();
    if (!name) {
      setDetailError("Name is required.");
      return;
    }

    const nextDescription = detailForm.description.trim();
    const normalizedNextDescription = nextDescription.length > 0 ? nextDescription : null;
    const normalizedInitialDescription =
      detailInitial.description.trim().length > 0 ? detailInitial.description.trim() : null;

    const dto: UpdateTeamDto = {};

    if (name !== detailInitial.name) {
      dto.name = name;
    }

    if (normalizedNextDescription !== normalizedInitialDescription) {
      dto.description = normalizedNextDescription;
    }

    if (Object.keys(dto).length === 0) {
      resetTeamDetails();
      return;
    }

    try {
      setIsSavingDetails(true);
      setDetailError(null);
      await updateTeam(detailTarget.id, dto);
      resetTeamDetails();
      await loadTeams(false);
    } catch (err: unknown) {
      setDetailError(err instanceof Error ? err.message : "Failed to update team");
    } finally {
      setIsSavingDetails(false);
    }
  }

  async function confirmDelete(): Promise<void> {
    if (!deleteTarget) {
      return;
    }

    try {
      setIsDeleting(true);
      await deleteTeam(deleteTarget.id);
      setDeleteTarget(null);
      await loadTeams(false);
      setError(null);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to delete team");
    } finally {
      setIsDeleting(false);
    }
  }

  if (isAdmin === null) {
    return (
      <Card className="max-w-2xl mx-auto mt-8">
        <CardContent className="py-12 text-center text-muted-foreground">
          Checking permissions...
        </CardContent>
      </Card>
    );
  }

  if (!isAdmin) {
    return <SettingsAccessDenied message="You need Admin or Owner role to manage teams." />;
  }

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold">Teams</h1>
            <Badge variant="outline">{teams.length} total</Badge>
          </div>
          <p className="text-muted-foreground mt-1">Create and manage workspace teams</p>
        </div>

        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            onClick={() => {
              void loadTeams(false);
            }}
            disabled={isLoading || isRefreshing}
          >
            {isRefreshing ? "Refreshing..." : "Refresh"}
          </Button>

          <Dialog
            open={isCreateOpen}
            onOpenChange={(open) => {
              if (!open && !isCreating) {
                resetCreateForm();
              }
              setIsCreateOpen(open);
            }}
          >
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Create Team
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Create Team</DialogTitle>
                <DialogDescription>
                  Create a team in the active workspace to organize members and permissions.
                </DialogDescription>
              </DialogHeader>

              <form
                onSubmit={(event) => {
                  void handleCreateSubmit(event);
                }}
                className="space-y-4"
              >
                <div className="space-y-2">
                  <Label htmlFor="create-name">Name</Label>
                  <Input
                    id="create-name"
                    value={createForm.name}
                    onChange={(event: ChangeEvent<HTMLInputElement>) => {
                      setCreateForm((prev) => ({ ...prev, name: event.target.value }));
                    }}
                    placeholder="Platform Team"
                    maxLength={100}
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="create-description">Description</Label>
                  <Textarea
                    id="create-description"
                    value={createForm.description}
                    onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
                      setCreateForm((prev) => ({ ...prev, description: event.target.value }));
                    }}
                    placeholder="Owns platform services and infrastructure"
                    maxLength={500}
                    rows={4}
                  />
                </div>

                {createError ? (
                  <p className="text-sm text-destructive" role="alert">
                    {createError}
                  </p>
                ) : null}

                <DialogFooter>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      if (!isCreating) {
                        setIsCreateOpen(false);
                        resetCreateForm();
                      }
                    }}
                    disabled={isCreating}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" disabled={isCreating}>
                    {isCreating ? "Creating..." : "Create Team"}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      <div>
        <Link href="/settings" className="text-sm text-blue-600 hover:text-blue-700">
          ← Back to Settings
        </Link>
      </div>

      {error ? (
        <Card>
          <CardContent className="py-4">
            <p className="text-sm text-destructive" role="alert">
              {error}
            </p>
          </CardContent>
        </Card>
      ) : null}

      {isLoading ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            Loading teams...
          </CardContent>
        </Card>
      ) : teams.length === 0 ? (
        <Card>
          <CardHeader>
            <CardTitle>No Teams Yet</CardTitle>
            <CardDescription>Create the first team to get started.</CardDescription>
          </CardHeader>
        </Card>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>Team Directory</CardTitle>
            <CardDescription>
              Click a team to view details or edit name and description.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {teams.map((team) => {
              const memberCount = team._count?.members ?? 0;
              const description = team.description?.trim();

              return (
                <div
                  key={team.id}
                  className="rounded-md border p-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between cursor-pointer hover:bg-muted/30"
                  role="button"
                  tabIndex={0}
                  onClick={() => {
                    openTeamDetails(team);
                  }}
                  onKeyDown={(event) => {
                    handleTeamRowKeyDown(event, team);
                  }}
                >
                  <div className="space-y-1 min-w-0">
                    <p className="font-semibold truncate">{team.name}</p>
                    <p className="text-sm text-muted-foreground truncate">
                      {description && description.length > 0 ? description : "No description"}
                    </p>
                  </div>

                  <div className="flex items-center gap-2 flex-wrap md:justify-end">
                    <Badge variant="outline">
                      <Users className="h-3.5 w-3.5 mr-1" />
                      {toMemberLabel(memberCount)}
                    </Badge>
                    <Badge variant="secondary">
                      Created {new Date(team.createdAt).toLocaleDateString()}
                    </Badge>
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={(event) => {
                        event.stopPropagation();
                        setDeleteTarget(team);
                      }}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Delete
                    </Button>
                  </div>
                </div>
              );
            })}
          </CardContent>
        </Card>
      )}

      <Dialog
        open={detailTarget !== null}
        onOpenChange={(open) => {
          if (!open && !isSavingDetails) {
            resetTeamDetails();
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Team Details</DialogTitle>
            <DialogDescription>
              Edit team details for {detailTarget?.name ?? "selected team"}.
            </DialogDescription>
          </DialogHeader>

          <form
            onSubmit={(event) => {
              void handleDetailSubmit(event);
            }}
            className="space-y-4"
          >
            <div className="space-y-2">
              <Label htmlFor="detail-name">Name</Label>
              <Input
                id="detail-name"
                value={detailForm.name}
                onChange={(event: ChangeEvent<HTMLInputElement>) => {
                  setDetailForm((prev) => ({ ...prev, name: event.target.value }));
                }}
                placeholder="Team name"
                maxLength={100}
                disabled={isSavingDetails}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="detail-description">Description</Label>
              <Textarea
                id="detail-description"
                value={detailForm.description}
                onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
                  setDetailForm((prev) => ({ ...prev, description: event.target.value }));
                }}
                placeholder="Describe this team"
                maxLength={500}
                rows={4}
                disabled={isSavingDetails}
              />
            </div>

            {detailError !== null ? (
              <p className="text-sm text-destructive" role="alert">
                {detailError}
              </p>
            ) : null}

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  if (!isSavingDetails) {
                    resetTeamDetails();
                  }
                }}
                disabled={isSavingDetails}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isSavingDetails}>
                {isSavingDetails ? "Saving..." : "Save Changes"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={deleteTarget !== null}
        onOpenChange={(open) => {
          if (!open && !isDeleting) {
            setDeleteTarget(null);
          }
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Team</AlertDialogTitle>
            <AlertDialogDescription>
              Delete {deleteTarget?.name}? Team members will be removed from this team assignment.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              disabled={isDeleting}
              onClick={() => {
                void confirmDelete();
              }}
            >
              {isDeleting ? "Deleting..." : "Delete Team"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
