import { Form } from "@remix-run/react";
import { useState } from "react";

interface ConnectDialogProps {
  network: {
    ssid: string;
    encrypted: boolean;
    signal_strength: number;
    _scannedPassword?: string;  // Pre-filled from QR scan
  } | null;
  onClose: () => void;
  isSubmitting: boolean;
}

export default function ConnectDialog({ network, onClose, isSubmitting }: ConnectDialogProps) {
  // Initialize password from QR scan if provided
  const [password, setPassword] = useState(network?._scannedPassword || "");
  const [showPassword, setShowPassword] = useState(false);
  // Start in hidden mode if no network is provided (user wants to enter SSID manually)
  const [hidden, setHidden] = useState(!network);
  const [customSSID, setCustomSSID] = useState(network?.ssid || "");

  if (!network && !hidden) return null;

  const ssid = hidden ? customSSID : network?.ssid || "";
  const needsPassword = hidden || (network?.encrypted ?? false);

  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: "rgba(10, 14, 26, 0.9)",
        backdropFilter: "blur(8px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 200,
        padding: "var(--space-4)",
      }}
      onClick={onClose}
    >
      <div
        className="card"
        style={{
          maxWidth: "500px",
          width: "100%",
          margin: 0,
          animation: "toast-in 250ms ease",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <h3 className="card-title" style={{ marginBottom: "var(--space-4)" }}>
          <span style={{ color: "var(--color-primary)" }}>📡</span>{" "}
          Connect to WiFi
        </h3>

        <Form method="post">
          <input type="hidden" name="_action" value="connect_network" />

          {/* SSID Input (for hidden networks) */}
          {!hidden ? (
            <>
              <div className="form-group">
                <label className="label">Network</label>
                <div
                  style={{
                    padding: "var(--space-3)",
                    background: "var(--color-bg)",
                    border: "1px solid var(--color-border)",
                    borderRadius: "var(--radius)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                  }}
                >
                  <div>
                    <div style={{ fontWeight: 600 }}>{network?.ssid}</div>
                    <div style={{ fontSize: "0.75rem", color: "var(--color-text-muted)" }}>
                      {network?.encrypted ? "🔒 Secured" : "Unsecured"}
                      {" • "}
                      {network?.signal_strength} dBm
                    </div>
                  </div>
                </div>
                <input type="hidden" name="ssid" value={network?.ssid || ""} />
              </div>

              <div style={{ textAlign: "center", marginBottom: "var(--space-4)" }}>
                <button
                  type="button"
                  className="btn btn-secondary"
                  style={{ fontSize: "0.75rem", padding: "var(--space-2) var(--space-3)" }}
                  onClick={() => setHidden(true)}
                >
                  Connect to hidden network instead
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="form-group">
                <label htmlFor="ssid" className="label">
                  Network Name (SSID)
                </label>
                <input
                  type="text"
                  id="ssid"
                  name="ssid"
                  className="input"
                  placeholder="Enter network name"
                  value={customSSID}
                  onChange={(e) => setCustomSSID(e.target.value)}
                  required
                  autoFocus
                />
              </div>

              <div style={{ textAlign: "center", marginBottom: "var(--space-4)" }}>
                <button
                  type="button"
                  className="btn btn-secondary"
                  style={{ fontSize: "0.75rem", padding: "var(--space-2) var(--space-3)" }}
                  onClick={() => setHidden(false)}
                >
                  ← Back to scanned networks
                </button>
              </div>
            </>
          )}

          {/* Password Input */}
          {needsPassword && (
            <div className="form-group">
              <label htmlFor="password" className="label">
                Password
              </label>
              <div style={{ position: "relative" }}>
                <input
                  type={showPassword ? "text" : "password"}
                  id="password"
                  name="password"
                  className="input"
                  placeholder="Enter network password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required={needsPassword}
                  autoComplete="off"
                  style={{ paddingRight: "3rem" }}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  style={{
                    position: "absolute",
                    right: "var(--space-3)",
                    top: "50%",
                    transform: "translateY(-50%)",
                    background: "transparent",
                    border: "none",
                    color: "var(--color-text-secondary)",
                    cursor: "pointer",
                    fontSize: "1.25rem",
                  }}
                  aria-label={showPassword ? "Hide password" : "Show password"}
                >
                  {showPassword ? "👁" : "👁‍🗨"}
                </button>
              </div>
            </div>
          )}

          {/* Hidden Network Checkbox */}
          <input type="hidden" name="hidden" value={hidden ? "true" : "false"} />

          {/* Actions */}
          <div style={{ display: "flex", gap: "var(--space-2)", marginTop: "var(--space-6)" }}>
            <button
              type="button"
              className="btn btn-secondary"
              style={{ flex: 1 }}
              onClick={onClose}
              disabled={isSubmitting}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="btn btn-primary"
              style={{ flex: 1 }}
              disabled={isSubmitting || (!ssid || (needsPassword && !password))}
            >
              {isSubmitting ? (
                <>
                  <span className="spinner"></span>
                  <span>Connecting...</span>
                </>
              ) : (
                <>
                  <span>✓</span>
                  <span>Connect</span>
                </>
              )}
            </button>
          </div>
        </Form>

        {needsPassword && (
          <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-4)", textAlign: "center" }}>
            Your password will be securely stored
          </p>
        )}
      </div>
    </div>
  );
}
