import { useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import { createHousehold, joinHousehold } from "../../api/households";
import { HouseholdContext } from "../../context/HouseholdContext";
import useActionToast from "../../hooks/useActionToast";
import getApiErrorMessage from "../../lib/getApiErrorMessage";
import "../../styles/components/manage/CreateJoinHousehold.css";

export default function CreateJoinHousehold({ onClose }) {
  const navigate = useNavigate();
  const toast = useActionToast();
  const { refreshHouseholds } = useContext(HouseholdContext);
  const [mode, setMode] = useState("create");
  const [householdName, setHouseholdName] = useState("");
  const [inviteCode, setInviteCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const extractInviteToken = (value) => {
    const trimmed = value.trim();
    if (!trimmed) return null;

    const directMatch = trimmed.match(/^\/?invite\/([a-zA-Z0-9]+)$/);
    if (directMatch) return directMatch[1];

    try {
      const parsed = new URL(trimmed, window.location.origin);
      const urlMatch = parsed.pathname.match(/^\/invite\/([a-zA-Z0-9]+)$/);
      if (urlMatch) return urlMatch[1];
    } catch (error) {
      return null;
    }

    return null;
  };

  const handleCreate = async (e) => {
    e.preventDefault();
    if (!householdName.trim()) return;

    setLoading(true);
    setError("");

    try {
      await createHousehold(householdName);
      await refreshHouseholds();
      toast.success("Created household", `Created household ${householdName.trim()}`);
      onClose();
    } catch (err) {
      console.error("Failed to create household:", err);
      const message = getApiErrorMessage(err, "Failed to create household");
      setError(message);
      toast.error("Create household failed", `Create household failed: ${message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleJoin = async (e) => {
    e.preventDefault();
    if (!inviteCode.trim()) return;

    setLoading(true);
    setError("");

    try {
      const inviteToken = extractInviteToken(inviteCode);
      if (inviteToken) {
        toast.info("Invite link detected", "Opening invite details");
        onClose();
        navigate(`/invite/${inviteToken}`);
        return;
      }

      await joinHousehold(inviteCode);
      await refreshHouseholds();
      toast.success("Joined household", "Joined household successfully");
      onClose();
    } catch (err) {
      console.error("Failed to join household:", err);
      const message = getApiErrorMessage(err, "Failed to join household");
      setError(message);
      toast.error("Join household failed", `Join household failed: ${message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="create-join-modal-overlay" onClick={onClose}>
      <div className="create-join-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>Household</h2>
          <button className="close-btn" onClick={onClose}>&times;</button>
        </div>

        <div className="mode-tabs">
          <button
            className={`mode-tab ${mode === "create" ? "active" : ""}`}
            onClick={() => setMode("create")}
          >
            Create New
          </button>
          <button
            className={`mode-tab ${mode === "join" ? "active" : ""}`}
            onClick={() => setMode("join")}
          >
            Join Existing
          </button>
        </div>

        {error && <div className="error-message">{error}</div>}

        {mode === "create" ? (
          <form onSubmit={handleCreate} className="household-form">
            <div className="form-group">
              <label htmlFor="householdName">Household Name</label>
              <input
                id="householdName"
                type="text"
                value={householdName}
                onChange={(e) => setHouseholdName(e.target.value)}
                placeholder="e.g., Smith Family"
                required
                autoFocus
              />
            </div>
            <div className="form-actions">
              <button type="button" onClick={onClose} className="btn-secondary">
                Cancel
              </button>
              <button type="submit" className="btn-primary" disabled={loading}>
                {loading ? "Creating..." : "Create Household"}
              </button>
            </div>
          </form>
        ) : (
          <form onSubmit={handleJoin} className="household-form">
            <div className="form-group">
              <label htmlFor="inviteCode">Invite Code or Link</label>
              <input
                id="inviteCode"
                type="text"
                value={inviteCode}
                onChange={(e) => setInviteCode(e.target.value)}
                placeholder="Invite code or /invite URL"
                required
                autoFocus
              />
              <p className="form-hint">
                Paste a raw invite code or full invite link URL
              </p>
            </div>
            <div className="form-actions">
              <button type="button" onClick={onClose} className="btn-secondary">
                Cancel
              </button>
              <button type="submit" className="btn-primary" disabled={loading}>
                {loading ? "Joining..." : "Join Household"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
