"use client";

import { useEffect, useState } from "react";
import { changePassword, getActiveSessions, Session } from "@/lib/api";
import { Shield, Smartphone, Monitor, LogOut } from "lucide-react";

export function AccountTab() {
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [changingPassword, setChangingPassword] = useState(false);
  const [pwdMsg, setPwdMsg] = useState("");

  const [sessions, setSessions] = useState<Session[]>([]);
  const [loadingSessions, setLoadingSessions] = useState(true);

  const [twoFAEnabled, setTwoFAEnabled] = useState(false);
  const [twoFASetup, setTwoFASetup] = useState(false);

  useEffect(() => {
    getActiveSessions()
      .then(setSessions)
      .catch(() => setSessions([]))
      .finally(() => setLoadingSessions(false));
  }, []);

  const handleChangePassword = () => {
    if (newPassword !== confirmPassword) {
      setPwdMsg("Passwords do not match.");
      return;
    }
    if (newPassword.length < 8) {
      setPwdMsg("New password must be at least 8 characters.");
      return;
    }
    setChangingPassword(true);
    setPwdMsg("");
    changePassword(currentPassword, newPassword)
      .then(() => {
        setPwdMsg("Password changed successfully!");
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
        setTimeout(() => setPwdMsg(""), 3000);
      })
      .catch((e) => setPwdMsg(`Error: ${e.message}`))
      .finally(() => setChangingPassword(false));
  };

  const getDeviceIcon = (device: string) => {
    if (device.toLowerCase().includes("mobile") || device.toLowerCase().includes("android") || device.toLowerCase().includes("ios")) {
      return Smartphone;
    }
    return Monitor;
  };

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleString();
    } catch {
      return dateStr;
    }
  };

  return (
    <div className="space-y-6">
      {/* Change password */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
          <Shield size={16} className="text-slack-purple" />
          Change Password
        </h3>
        <div className="space-y-3 max-w-md">
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">Current password</label>
            <input
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">New password</label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">Confirm new password</label>
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-sm"
            />
          </div>
          {pwdMsg && (
            <p className={`text-sm ${pwdMsg.includes("Error") || pwdMsg.includes("not match") ? "text-slack-red" : "text-slack-green"}`}>
              {pwdMsg}
            </p>
          )}
          <button
            onClick={handleChangePassword}
            disabled={changingPassword || !currentPassword || !newPassword}
            className="px-4 py-2 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
          >
            {changingPassword ? "Changing..." : "Change password"}
          </button>
        </div>
      </div>

      {/* 2FA */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
          <Shield size={16} className="text-slack-purple" />
          Two-Factor Authentication
        </h3>
        {twoFAEnabled ? (
          <div className="flex items-center gap-3">
            <span className="inline-flex items-center gap-1 text-sm text-slack-green font-medium">
              <Shield size={14} />
              2FA is enabled
            </span>
            <button
              onClick={() => setTwoFAEnabled(false)}
              className="text-sm text-slack-red hover:underline"
            >
              Disable
            </button>
          </div>
        ) : twoFASetup ? (
          <div className="space-y-3">
            <div className="w-32 h-32 bg-gray-100 rounded-lg flex items-center justify-center mx-auto">
              <p className="text-xs text-gray-400 text-center">QR Code (stub)</p>
            </div>
            <p className="text-sm text-gray-600 text-center">
              Scan the QR code with your authenticator app to set up 2FA.
            </p>
            <div className="flex justify-center gap-2">
              <button
                onClick={() => {
                  setTwoFAEnabled(true);
                  setTwoFASetup(false);
                }}
                className="px-4 py-2 rounded-md bg-slack-green text-white text-sm font-medium hover:opacity-90 transition-colors"
              >
                Confirm Setup
              </button>
              <button
                onClick={() => setTwoFASetup(false)}
                className="px-4 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-600 hover:bg-gray-50"
              >
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-3">
            <span className="text-sm text-gray-600">2FA is not enabled.</span>
            <button
              onClick={() => setTwoFASetup(true)}
              className="px-4 py-1.5 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors"
            >
              Set up 2FA
            </button>
          </div>
        )}
      </div>

      {/* Active sessions */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
          <Smartphone size={16} className="text-slack-purple" />
          Active Sessions
        </h3>
        {loadingSessions ? (
          <div className="text-sm text-gray-400 animate-pulse">Loading sessions...</div>
        ) : sessions.length === 0 ? (
          <p className="text-sm text-gray-400">No active sessions found.</p>
        ) : (
          <div className="space-y-3">
            {sessions.map((session) => {
              const Icon = getDeviceIcon(session.device || "Desktop");
              return (
                <div
                  key={session.id}
                  className="flex items-center justify-between p-3 rounded-md border border-gray-200"
                >
                  <div className="flex items-center gap-3">
                    <Icon size={20} className="text-gray-400" />
                    <div>
                      <p className="text-sm font-medium text-gray-700">
                        {session.device || "Desktop"}
                        {session.current && (
                          <span className="ml-2 text-xs bg-slack-green/10 text-slack-green px-2 py-0.5 rounded-md">
                            Current
                          </span>
                        )}
                      </p>
                      <p className="text-xs text-gray-400">
                        {session.ip} · Last active {formatDate(session.last_active)}
                      </p>
                    </div>
                  </div>
                  {!session.current && (
                    <button className="text-slack-red hover:bg-slack-red/10 p-2 rounded-md transition-colors">
                      <LogOut size={14} />
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}