"use client";

import { useState, useEffect, useCallback } from "react";
import { Modal, Button, Input, Select, Toggle, SegmentedControl } from "@/shared/components";

const CAVEMAN_LEVELS = [
  { value: "lite", label: "Lite" },
  { value: "full", label: "Full" },
  { value: "ultra", label: "Ultra" },
];

function generatePassword(length = 16) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
  const arr = new Uint8Array(length);
  crypto.getRandomValues(arr);
  return Array.from(arr, (b) => chars[b % chars.length]).join("");
}

export default function AddUserModal({ isOpen, onClose, onSuccess }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [packageId, setPackageId] = useState("");
  const [rtkEnabled, setRtkEnabled] = useState(false);
  const [cavemanEnabled, setCavemanEnabled] = useState(false);
  const [cavemanLevel, setCavemanLevel] = useState("lite");
  const [packages, setPackages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [result, setResult] = useState(null);
  const [copied, setCopied] = useState(false);

  // Fetch packages on mount / open
  useEffect(() => {
    if (!isOpen) return;
    (async () => {
      try {
        const res = await fetch("/api/packages");
        if (res.ok) {
          const data = await res.json();
          setPackages(data.packages || []);
        }
      } catch {
        // silent — packages are optional
      }
    })();
  }, [isOpen]);

  // Reset state when modal closes
  useEffect(() => {
    if (!isOpen) {
      setUsername("");
      setPassword("");
      setPackageId("");
      setRtkEnabled(false);
      setCavemanEnabled(false);
      setCavemanLevel("lite");
      setError("");
      setResult(null);
      setCopied(false);
    }
  }, [isOpen]);

  const handleGenerate = useCallback(() => {
    setPassword(generatePassword());
  }, []);

  const handleCopy = useCallback(async () => {
    if (!result?.apiKey?.key) return;
    try {
      await navigator.clipboard.writeText(result.apiKey.key);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // fallback — select & copy
      const el = document.getElementById("api-key-display");
      if (el) {
        const range = document.createRange();
        range.selectNodeContents(el);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand("copy");
        window.getSelection().removeAllRanges();
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }
    }
  }, [result]);

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();
      setError("");

      if (!username.trim()) {
        setError("Username is required");
        return;
      }
      if (!password) {
        setError("Password is required");
        return;
      }

      setLoading(true);
      try {
        const res = await fetch("/api/users/create-with-key", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            username: username.trim(),
            password,
            packageId: packageId || undefined,
            rtkEnabled,
            cavemanEnabled,
            cavemanLevel: cavemanEnabled ? cavemanLevel : null,
          }),
        });

        const data = await res.json();
        if (!res.ok) {
          throw new Error(data.error || "Failed to create user");
        }

        setResult(data);
        onSuccess?.();
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    },
    [username, password, packageId, rtkEnabled, cavemanEnabled, cavemanLevel, onSuccess]
  );

  const handleClose = useCallback(() => {
    if (loading) return;
    onClose();
  }, [loading, onClose]);

  // Package options for Select
  const packageOptions = packages.map((pkg) => ({
    value: pkg.id,
    label: pkg.name,
  }));

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      title={result ? "User Created" : "Add User"}
      size="md"
      closeOnOverlay={!loading}
      footer={
        result ? (
          <Button variant="primary" onClick={handleClose} fullWidth>
            Done
          </Button>
        ) : (
          <>
            <Button variant="ghost" onClick={handleClose} disabled={loading}>
              Cancel
            </Button>
            <Button
              type="submit"
              form="add-user-form"
              variant="primary"
              icon="person_add"
              loading={loading}
            >
              Create User
            </Button>
          </>
        )
      }
    >
      {result ? (
        <SuccessView
          result={result}
          copied={copied}
          onCopy={handleCopy}
        />
      ) : (
        <form id="add-user-form" onSubmit={handleSubmit} className="flex flex-col gap-4">
          {/* Username */}
          <Input
            label="Username"
            placeholder="e.g. johndoe"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            icon="person"
            required
            disabled={loading}
            autoFocus
          />

          {/* Password */}
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-text-main">
              Password<span className="text-red-500 ml-1">*</span>
            </label>
            <div className="flex gap-2">
              <Input
                type="text"
                placeholder="Enter or generate a password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                icon="lock"
                disabled={loading}
                className="flex-1"
              />
              <Button
                type="button"
                variant="secondary"
                icon="casino"
                onClick={handleGenerate}
                disabled={loading}
                className="shrink-0"
              >
                Auto
              </Button>
            </div>
            <p className="text-xs text-text-muted">16 characters with mixed case, numbers & symbols</p>
          </div>

          {/* Package */}
          <Select
            label="Package"
            options={packageOptions}
            value={packageId}
            onChange={(e) => setPackageId(e.target.value)}
            placeholder="No package (default limits)"
            disabled={loading}
          />

          {/* Divider */}
          <div className="border-t border-border-subtle" />

          {/* RTK Toggle */}
          <Toggle
            checked={rtkEnabled}
            onChange={setRtkEnabled}
            label="RTK Enabled"
            description="Enable Real-Time Kit integration for this user's API key"
            disabled={loading}
          />

          {/* Caveman Toggle + Level */}
          <div className="flex flex-col gap-3">
            <Toggle
              checked={cavemanEnabled}
              onChange={setCavemanEnabled}
              label="Caveman Mode"
              description="Enable Caveman reasoning mode for this user's API key"
              disabled={loading}
            />
            {cavemanEnabled && (
              <div className="ml-11">
                <SegmentedControl
                  options={CAVEMAN_LEVELS}
                  value={cavemanLevel}
                  onChange={setCavemanLevel}
                  size="sm"
                />
              </div>
            )}
          </div>

          {/* Error */}
          {error && (
            <div className="flex items-center gap-2 p-3 rounded-[10px] bg-red-500/10 border border-red-500/20 text-red-500 text-sm">
              <span className="material-symbols-outlined text-[18px]">error</span>
              {error}
            </div>
          )}
        </form>
      )}
    </Modal>
  );
}

function SuccessView({ result, copied, onCopy }) {
  const { apiKey, plainPassword } = result;

  return (
    <div className="flex flex-col gap-4">
      {/* Success banner */}
      <div className="flex items-center gap-3 p-3 rounded-[10px] bg-green-500/10 border border-green-500/20">
        <span className="material-symbols-outlined text-green-500 text-[20px]">check_circle</span>
        <p className="text-sm text-green-500 font-medium">
          User &quot;{result.user?.username}&quot; created successfully
        </p>
      </div>

      {/* API Key display */}
      <div className="flex flex-col gap-1.5">
        <label className="text-sm font-medium text-text-main">API Key</label>
        <div className="flex items-center gap-2">
          <code
            id="api-key-display"
            className="flex-1 px-3 py-2.5 text-xs font-mono text-text-main bg-surface-2 rounded-[10px] border border-border-subtle break-all select-all"
          >
            {apiKey?.key}
          </code>
          <Button
            variant={copied ? "success" : "secondary"}
            icon={copied ? "check" : "content_copy"}
            onClick={onCopy}
            className="shrink-0"
          >
            {copied ? "Copied" : "Copy"}
          </Button>
        </div>
        <p className="text-xs text-amber-500 flex items-center gap-1">
          <span className="material-symbols-outlined text-[14px]">warning</span>
          Save this key now — it will not be shown again
        </p>
      </div>

      {/* Password (shown for reference) */}
      {plainPassword && (
        <div className="flex flex-col gap-1.5">
          <label className="text-sm font-medium text-text-main">Password</label>
          <code className="px-3 py-2.5 text-xs font-mono text-text-muted bg-surface-2 rounded-[10px] border border-border-subtle break-all select-all">
            {plainPassword}
          </code>
        </div>
      )}

      {/* Feature flags summary */}
      <div className="flex flex-wrap gap-2">
        {apiKey?.rtkEnabled && (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-full bg-blue-500/10 text-blue-500 border border-blue-500/20">
            <span className="material-symbols-outlined text-[14px]">bolt</span>
            RTK
          </span>
        )}
        {apiKey?.cavemanEnabled && (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-full bg-orange-500/10 text-orange-500 border border-orange-500/20">
            <span className="material-symbols-outlined text-[14px]">psychology</span>
            Caveman ({apiKey.cavemanLevel})
          </span>
        )}
      </div>
    </div>
  );
}
