import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { motion } from "framer-motion";
import {
  Tv,
  Server,
  User,
  KeyRound,
  Link as LinkIcon,
  UserCircle,
  Loader2,
  Upload,
  FileText,
  X,
  Plus,
  Trash2,
  Globe2,
  Cpu,
} from "lucide-react";
import { useConnectProfile } from "@/hooks/useConnectProfile";
import StalkerTestButton from "@/components/StalkerTestButton";
import type { ProfileKind, ProfileTarget } from "@/types/xtream";

interface M3URow {
  key: string;
  name: string;
  url: string;
  content: string;
  fileName: string;
}

const newRow = (name = "", url = ""): M3URow => ({
  key: `r-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
  name,
  url,
  content: "",
  fileName: "",
});

/**
 * Public Xtream / M3U login page.
 * Supports deep linking via query params:
 *   /login?type=xtream&name=My&server=http://x.com&user=u&pass=p
 *   /login?type=m3u&name=My&url=https://x.com/playlist.m3u
 * If `auto=1`, the form auto-submits after prefill.
 */
const Login = () => {
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const connect = useConnectProfile();

  const [kind, setKind] = useState<ProfileKind>(
    (params.get("type") as ProfileKind) || "xtream",
  );
  const [name, setName] = useState(params.get("name") || "");
  const [serverUrl, setServerUrl] = useState(params.get("server") || "");
  const [username, setUsername] = useState(params.get("user") || "");
  const [password, setPassword] = useState(params.get("pass") || "");
  const [portalUrl, setPortalUrl] = useState(params.get("portal") || "");
  const [macAddress, setMacAddress] = useState(params.get("mac") || "");
  const [m3uRows, setM3uRows] = useState<M3URow[]>([
    newRow(params.get("name") || "", params.get("url") || ""),
  ]);
  const [submitting, setSubmitting] = useState(false);
  const [target, setTarget] = useState<ProfileTarget>("all");

  const formatMac = (raw: string): string => {
    const hex = raw.replace(/[^0-9A-Fa-f]/g, "").toUpperCase().slice(0, 12);
    return hex.match(/.{1,2}/g)?.join(":") ?? "";
  };

  const updateRow = (idx: number, patch: Partial<M3URow>) =>
    setM3uRows((prev) => prev.map((r, i) => (i === idx ? { ...r, ...patch } : r)));
  const addRow = () => setM3uRows((prev) => [...prev, newRow()]);
  const removeRow = (idx: number) =>
    setM3uRows((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== idx) : prev));

  const handleFile = async (idx: number, file: File | null) => {
    if (!file) return;
    const text = await file.text();
    updateRow(idx, { content: text, fileName: file.name });
  };

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();

    if (kind === "xtream") {
      if (!name || !serverUrl || !username || !password) return;
      setSubmitting(true);
      const created = await connect({
        kind,
        name,
        serverUrl,
        username,
        password,
        target,
      });
      setSubmitting(false);
      if (created) navigate("/");
      return;
    }

    if (kind === "stalker") {
      const macOk = /^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(macAddress.trim());
      if (!name || !portalUrl.trim() || !macOk) return;
      setSubmitting(true);
      const created = await connect({
        kind,
        name,
        serverUrl: "",
        username: "",
        password: "",
        portalUrl: portalUrl.trim(),
        macAddress: macAddress.trim().toUpperCase(),
        target,
      });
      setSubmitting(false);
      if (created) navigate("/");
      return;
    }

    // M3U: connect each row that has either a URL or uploaded content
    const valid = m3uRows
      .map((r, i) => ({
        ...r,
        name: (r.name || name || `Playlist ${i + 1}`).trim(),
        url: r.url.trim(),
      }))
      .filter((r) => r.url.length > 0 || r.content.trim().length > 0);

    if (valid.length === 0) return;

    setSubmitting(true);
    let lastCreated = null;
    for (const r of valid) {
      lastCreated = await connect({
        kind: "m3u",
        name: r.name,
        serverUrl: "",
        username: "",
        password: "",
        m3uUrl: r.url || undefined,
        m3uContent: r.content || undefined,
        target,
      });
    }
    setSubmitting(false);
    if (lastCreated) navigate("/");
  };

  useEffect(() => {
    if (params.get("auto") === "1") void handleSubmit();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="relative h-screen w-full overflow-hidden flex items-center justify-center px-4 py-8">
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="absolute inset-0 bg-background/60" />

      <motion.form
        onSubmit={handleSubmit}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative z-10 glass-card rounded-3xl p-8 w-full max-w-md"
      >
        <div className="flex flex-col items-center mb-6">
          <div className="w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3">
            <Tv className="w-6 h-6 text-primary" />
          </div>
          <h1 className="font-display text-2xl tracking-[0.25em] gold-text">
            NADIPLAYER
          </h1>
          <p className="text-muted-foreground text-xs mt-1">
            Connect your IPTV service
          </p>
        </div>

        <div className="flex glass rounded-xl p-1 mb-5">
          {(["xtream", "m3u", "stalker"] as ProfileKind[]).map((k) => (
            <button
              type="button"
              key={k}
              onClick={() => setKind(k)}
              data-testid={`kind-${k}`}
              className={`flex-1 py-2 rounded-lg text-xs font-medium transition-all ${
                kind === k ? "bg-primary/20 text-primary" : "text-muted-foreground"
              }`}
            >
              {k === "xtream"
                ? "Xtream"
                : k === "m3u"
                  ? "M3U"
                  : "Stalker"}
            </button>
          ))}
        </div>

        {/* Target Selector: what section this playlist is for */}
        <div className="flex glass rounded-xl p-1 mb-5">
          {([
            { val: "all", label: "All Content" },
            { val: "live", label: "Live TV Only" },
            { val: "vod", label: "Movies & Series" },
          ] as const).map(({ val, label }) => (
            <button
              type="button"
              key={val}
              onClick={() => setTarget(val)}
              data-testid={`target-${val}`}
              className={`flex-1 py-2 rounded-lg text-[10px] font-medium transition-all ${
                target === val
                  ? val === "live" ? "bg-primary/20 text-primary" : val === "vod" ? "bg-blue-500/20 text-blue-400" : "bg-primary/20 text-primary"
                  : "text-muted-foreground"
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        {kind === "xtream" ? (
          <div className="space-y-3">
            <Field
              icon={UserCircle}
              placeholder="Profile Name"
              value={name}
              onChange={setName}
            />
            <Field
              icon={Server}
              placeholder="Server URL (http://...)"
              value={serverUrl}
              onChange={setServerUrl}
            />
            <Field
              icon={User}
              placeholder="Username"
              value={username}
              onChange={setUsername}
            />
            <Field
              icon={KeyRound}
              placeholder="Password"
              value={password}
              onChange={setPassword}
              type="password"
            />
          </div>
        ) : kind === "stalker" ? (
          <div className="space-y-3" data-testid="login-stalker-form">
            <Field
              icon={UserCircle}
              placeholder="Profile Name"
              value={name}
              onChange={setName}
              testId="login-stalker-name"
            />
            <Field
              icon={Globe2}
              placeholder="Portal URL (http://portal.com:8080/c/)"
              value={portalUrl}
              onChange={setPortalUrl}
              testId="login-stalker-portal"
            />
            <Field
              icon={Cpu}
              placeholder="MAC Address (00:1A:79:XX:XX:XX)"
              value={macAddress}
              onChange={(v: string) => setMacAddress(formatMac(v))}
              testId="login-stalker-mac"
            />
            <StalkerTestButton
              portalUrl={portalUrl}
              mac={macAddress}
              testId="login-stalker-test"
            />
            <p className="text-[11px] text-muted-foreground leading-relaxed px-1">
              Stalker / MAG portal. Authenticates as a MAG250 STB using your MAC.
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {m3uRows.map((row, idx) => (
              <div
                key={row.key}
                data-testid={`login-m3u-row-${idx}`}
                className="glass rounded-xl p-3 border border-border/40 space-y-2"
              >
                <div className="flex items-center justify-between">
                  <span className="text-[10px] uppercase tracking-widest text-primary/80">
                    Playlist #{idx + 1}
                  </span>
                  {m3uRows.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeRow(idx)}
                      data-testid={`login-m3u-row-remove-${idx}`}
                      className="text-muted-foreground hover:text-destructive transition-colors"
                      aria-label="Remove row"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  )}
                </div>
                <Field
                  icon={UserCircle}
                  placeholder="Profile Name"
                  value={row.name}
                  onChange={(v) => updateRow(idx, { name: v })}
                />
                <Field
                  icon={LinkIcon}
                  placeholder="https://example.com/playlist.m3u"
                  value={row.url}
                  onChange={(v) => updateRow(idx, { url: v })}
                />
                <div className="flex items-center gap-2 flex-wrap">
                  <label
                    data-testid={`login-m3u-file-${idx}`}
                    className="cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors"
                  >
                    <Upload className="w-3.5 h-3.5" />
                    <span>Upload .m3u file</span>
                    <input
                      type="file"
                      accept=".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain"
                      onChange={(e) =>
                        void handleFile(idx, e.target.files?.[0] ?? null)
                      }
                      className="hidden"
                    />
                  </label>
                  {row.content && row.content.trim().length > 0 && (
                    <div className="flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground">
                      <FileText className="w-3.5 h-3.5 text-primary shrink-0" />
                      <span className="truncate">
                        {row.fileName || "uploaded.m3u"}
                      </span>
                      <button
                        type="button"
                        onClick={() =>
                          updateRow(idx, { content: "", fileName: "" })
                        }
                        className="ml-1 text-muted-foreground hover:text-destructive"
                      >
                        <X className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
            <button
              type="button"
              onClick={addRow}
              data-testid="login-add-m3u-row-btn"
              className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl border border-dashed border-primary/40 text-primary hover:bg-primary/10 transition-colors text-xs font-medium tracking-[0.2em] uppercase"
            >
              <Plus className="w-4 h-4" /> Add Playlist
            </button>
          </div>
        )}

        <button
          type="submit"
          aria-busy={submitting || undefined}
          data-loading={submitting || undefined}
          onClick={(e) => { if (submitting) e.preventDefault(); }}
          className={`w-full mt-6 py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 ${submitting ? "opacity-60 pointer-events-none cursor-wait" : ""}`}
          data-testid="connect-profile-submit-btn"
        >
          {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
          {submitting ? "Connecting..." : "Connect & Load"}
        </button>

        <button
          type="button"
          onClick={() => navigate("/")}
          className="w-full mt-3 text-muted-foreground text-xs hover:text-foreground transition-colors"
        >
          Skip for now
        </button>
      </motion.form>
    </div>
  );
};

const Field = ({ icon: Icon, placeholder, value, onChange, type = "text", testId }: any) => (
  <div className="flex items-center gap-3 glass-input rounded-xl px-4 py-3">
    <Icon className="w-5 h-5 text-muted-foreground shrink-0" />
    <input
      type={type}
      placeholder={placeholder}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      data-testid={testId}
      className="flex-1 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm"
      autoComplete="off"
    />
  </div>
);

export default Login;
