import React, { useState, KeyboardEvent, useRef, useContext } from "react";
import "./NameSetter.css";
import pokTitle from "./assets/pok-title.png";
import {
  Input,
  Button,
  Box,
  Typography,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Paper,
} from "@mui/material";
import { GlobalContext, Session } from "./GlobalContext";

interface NameSetterProps {
  onNameSet?: () => void;
  initialName?: string;
  initialPassword?: string;
}

const NameSetter: React.FC<NameSetterProps> = ({ onNameSet, initialName = "", initialPassword = "" }) => {
  const { session, sendJsonMessage } = useContext(GlobalContext);
  const [editName, setEditName] = useState<string>(initialName);
  const [editPassword, setEditPassword] = useState<string>(initialPassword);
  const [showDialog, setShowDialog] = useState<boolean>(!session.name);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);

  const nameInputRef = useRef<HTMLInputElement>(null);
  const passwordInputRef = useRef<HTMLInputElement>(null);

  const setName = (name: string) => {
    setIsSubmitting(true);
    sendJsonMessage({
      type: "player-name",
      data: { name, password: editPassword ? editPassword : undefined },
    });
    if (onNameSet) {
      onNameSet();
    }
    setShowDialog(false);
    setIsSubmitting(false);
    setEditName("");
    setEditPassword("");
  };

  const handleNameKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
    if (event.key === "Enter") {
      event.preventDefault();
      if (passwordInputRef.current) {
        passwordInputRef.current.focus();
      } else {
        // No password input present — submit the name directly
        handleSubmit();
      }
    }
  };

  const handlePasswordKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
    if (event.key === "Enter") {
      event.preventDefault();
      handleSubmit();
    }
  };

  const handleSubmit = () => {
    const newName = editName.trim();
    if (!newName || (session?.name && session.name === newName)) {
      return;
    }
    setName(newName);
  };

  const hasNameChanged = editName.trim() !== (session.name || "");
  const canSubmit = editName.trim() && hasNameChanged && !isSubmitting;

  return (
    <Box
      className="NameSetter-root"
      sx={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        maxWidth: "800px",
        maxHeight: "100dvh",
        width: "100%",
        height: "100dvh",
        margin: "auto",
        backgroundImage: `url(${pokTitle})`,
        backgroundRepeat: "no-repeat",
        backgroundPosition: "top center",
        backgroundSize: "cover",
      }}
    >
      <Paper
        sx={{
          position: "absolute",
          bottom: "10%",
          width: "calc(100% - 2rem)",
          backgroundColor: "rgba(255, 255, 255, 0.8) !important",
        }}
      >
        <DialogTitle className="NameSetter-dialogTitle">
          {session.name ? "Change Your Name" : "How shall you be called?"}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, pt: 1 }}>
            <Input
              inputRef={nameInputRef}
              type="text"
              value={editName}
              onChange={(e): void => {
                setEditName(e.target.value);
              }}
              onKeyDown={handleNameKeyDown}
              placeholder="Your quipy handle"
              fullWidth
              autoFocus
              className="NameSetter-nameInput"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          {/* <Button onClick={handleCloseDialog} disabled={isSubmitting}>
            Cancel
          </Button> */}
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={!canSubmit}
            color={hasNameChanged ? "primary" : "inherit"}
            sx={
              hasNameChanged
                ? {
                    backgroundColor: "primary.main",
                    color: "#444",
                    "&:hover": { backgroundColor: "primary.dark", color: "#fff" },
                  }
                : undefined
            }
          >
            {isSubmitting ? "Changing..." : session.name ? "Change Name" : "Enter Ketran!"}
          </Button>
        </DialogActions>
      </Paper>
    </Box>
  );
};

export default NameSetter;
