"use client";

import { useState, useTransition } from "react";
import Link from "next/link";

interface LoginSession {
  id: string;
  loginTime: Date;
  ipAddress: string;
  device: string;
  location: string;
  status: "success" | "failed";
}

interface SecurityEvent {
  id: string;
  event: string;
  detail: string;
  timestamp: Date;
  icon: string;
  color: string;
}

interface SerializedLoginSession {
  id: string;
  loginTime: string;
  ipAddress: string;
  device: string;
  location: string;
  status: "success" | "failed";
}

interface SerializedSecurityEvent {
  id: string;
  event: string;
  detail: string;
  timestamp: string;
  icon: string;
  color: string;
}

interface AccountSecurityProps {
  displayName: string;
  email: string;
  loginSessions?: SerializedLoginSession[];
  securityEvents?: SerializedSecurityEvent[];
  twoFactorEnabled?: boolean;
  initialLoginNotifications?: boolean;
  activeSessionCount?: number;
}

export default function AccountSecurity({
  displayName,
  email,
  loginSessions: propSessions,
  securityEvents: propEvents,
  twoFactorEnabled: propTwoFactor,
  initialLoginNotifications,
  activeSessionCount = 0,
}: AccountSecurityProps) {
  const [isPending, startTransition] = useTransition();
  const [activeTab, setActiveTab] = useState<"overview" | "sessions" | "log">("overview");
  const [twoFactorEnabled, setTwoFactorEnabled] = useState(propTwoFactor ?? false);
  const [loginNotifications, setLoginNotifications] = useState(initialLoginNotifications ?? true);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Use real Keycloak data if available, otherwise empty
  const sessions: LoginSession[] = (propSessions ?? []).map((s) => ({
    ...s,
    loginTime: new Date(s.loginTime),
  }));

  const securityEventsList: SecurityEvent[] = (propEvents ?? []).map((e) => ({
    ...e,
    timestamp: new Date(e.timestamp),
  }));

  const formatDateTime = (date: Date) => {
    return date.toLocaleString("en-US", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatRelativeTime = (date: Date) => {
    const diff = Date.now() - date.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return "Just now";
    if (minutes < 60) return `${minutes}m ago`;
    if (hours < 24) return `${hours}h ago`;
    if (days < 7) return `${days}d ago`;
    return formatDateTime(date);
  };

  const handleSave = () => {
    startTransition(async () => {
      try {
        const { saveSecuritySettings } = await import("@/app/actions/security");
        const result = await saveSecuritySettings({ loginNotifications });
        if (result.error) {
          setMessage({ type: "error", text: result.error });
        } else {
          setMessage({ type: "success", text: result.message || "Security settings updated successfully." });
        }
      } catch {
        setMessage({ type: "error", text: "Failed to save security settings." });
      }
      setTimeout(() => setMessage(null), 5000);
    });
  };

  const successLogins = sessions.filter((s) => s.status === "success").length;
  const failedLogins = sessions.filter((s) => s.status === "failed").length;
  const uniqueDevices = new Set(sessions.map((s) => s.device)).size;

  return (
    <>
      {/* Page Header */}
      <div className="d-flex align-items-center justify-content-between mb-4">
        <div className="d-flex align-items-center">
          <Link href="/" className="btn btn-light btn-sm me-3">
            <i className="ph-arrow-left"></i>
          </Link>
          <div>
            <h4 className="mb-0">
              <i className="ph-shield-check me-2"></i>
              Account Security
            </h4>
            <p className="text-muted mb-0 mt-1">Manage your security settings, sessions, and authentication methods.</p>
          </div>
        </div>
        <button className="btn btn-primary" onClick={handleSave} disabled={isPending}>
          {isPending ? (
            <>
              <span className="spinner-border spinner-border-sm me-2"></span>
              Saving...
            </>
          ) : (
            <>
              <i className="ph-floppy-disk me-2"></i>
              Save Changes
            </>
          )}
        </button>
      </div>

      {/* Alert */}
      {message && (
        <div
          className={`alert ${message.type === "success" ? "alert-success" : "alert-danger"} alert-dismissible`}
          role="alert"
        >
          <i className={`ph-${message.type === "success" ? "check-circle" : "warning"} me-2`}></i>
          {message.text}
          <button type="button" className="btn-close" onClick={() => setMessage(null)}></button>
        </div>
      )}

      {/* Summary Cards */}
      <div className="row mb-4">
        <div className="col-sm-6 col-xl-3">
          <div className="card card-body">
            <div className="d-flex align-items-center">
              <div className="flex-fill">
                <h4 className="mb-0">{successLogins}</h4>
                <span className="text-muted">Successful Logins</span>
              </div>
              <i className="ph-sign-in ph-2x text-success opacity-75"></i>
            </div>
          </div>
        </div>
        <div className="col-sm-6 col-xl-3">
          <div className="card card-body">
            <div className="d-flex align-items-center">
              <div className="flex-fill">
                <h4 className="mb-0">{failedLogins}</h4>
                <span className="text-muted">Failed Attempts</span>
              </div>
              <i className="ph-warning ph-2x text-danger opacity-75"></i>
            </div>
          </div>
        </div>
        <div className="col-sm-6 col-xl-3">
          <div className="card card-body">
            <div className="d-flex align-items-center">
              <div className="flex-fill">
                <h4 className="mb-0">{uniqueDevices}</h4>
                <span className="text-muted">Known Devices</span>
              </div>
              <i className="ph-devices ph-2x text-primary opacity-75"></i>
            </div>
          </div>
        </div>
        <div className="col-sm-6 col-xl-3">
          <div className="card card-body">
            <div className="d-flex align-items-center">
              <div className="flex-fill">
                <h4 className="mb-0">{twoFactorEnabled ? "On" : "Off"}</h4>
                <span className="text-muted">Two-Factor Auth</span>
              </div>
              <i className={`ph-shield-check ph-2x ${twoFactorEnabled ? "text-success" : "text-warning"} opacity-75`}></i>
            </div>
          </div>
        </div>
      </div>

      <div className="row">
        {/* Left Column */}
        <div className="col-xl-8">
          {/* Tabs Card */}
          <div className="card">
            <div className="card-header">
              <ul className="nav nav-tabs card-header-tabs">
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "overview" ? "active" : ""}`}
                    onClick={() => setActiveTab("overview")}
                  >
                    <i className="ph-shield me-2"></i>
                    Security Settings
                  </button>
                </li>
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "sessions" ? "active" : ""}`}
                    onClick={() => setActiveTab("sessions")}
                  >
                    <i className="ph-devices me-2"></i>
                    Login Sessions
                  </button>
                </li>
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "log" ? "active" : ""}`}
                    onClick={() => setActiveTab("log")}
                  >
                    <i className="ph-clock-counter-clockwise me-2"></i>
                    Security Log
                  </button>
                </li>
              </ul>
            </div>

            <div className="card-body">
              {/* Security Settings Tab */}
              {activeTab === "overview" && (
                <>
                  <h5 className="mb-3">
                    <i className="ph-key me-2"></i>
                    Password
                  </h5>
                  <div className="d-flex align-items-center p-3 bg-light rounded mb-4">
                    <div className="bg-success bg-opacity-10 text-success rounded-pill p-2 me-3">
                      <i className="ph-check"></i>
                    </div>
                    <div className="flex-fill">
                      <div className="fw-medium">Password is set</div>
                      <small className="text-muted">Managed by your identity provider</small>
                    </div>
                    <a
                      href={`${process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER || "https://auth.gosec.cloud/realms/gosecCloud"}/account/#/security/signingin`}
                      target="_blank"
                      rel="noreferrer"
                      className="btn btn-outline-primary btn-sm"
                    >
                      <i className="ph-key me-1"></i>
                      Change Password
                    </a>
                  </div>

                  <h5 className="mb-3">
                    <i className="ph-shield-check me-2"></i>
                    Two-Factor Authentication
                  </h5>
                  <div className="d-flex justify-content-between align-items-start py-3 border-bottom">
                    <div className="me-3">
                      <div className="fw-medium">Enable two-factor authentication</div>
                      <small className="text-muted">Add an extra layer of security with TOTP authenticator app</small>
                    </div>
                    <label className="form-check form-switch mb-0">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        checked={twoFactorEnabled}
                        onChange={(e) => setTwoFactorEnabled(e.target.checked)}
                      />
                    </label>
                  </div>
                  <div className="d-flex justify-content-between align-items-start py-3 border-bottom">
                    <div className="me-3">
                      <div className="fw-medium">Login notifications</div>
                      <small className="text-muted">Get notified when someone logs into your account from a new device</small>
                    </div>
                    <label className="form-check form-switch mb-0">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        checked={loginNotifications}
                        onChange={(e) => setLoginNotifications(e.target.checked)}
                      />
                    </label>
                  </div>

                  {!twoFactorEnabled && (
                    <div className="alert alert-warning mt-3 mb-0">
                      <i className="ph-warning me-2"></i>
                      Two-factor authentication is not enabled. We strongly recommend enabling it for better account protection.
                    </div>
                  )}
                </>
              )}

              {/* Sessions Tab */}
              {activeTab === "sessions" && (
                <>
                  <div className="d-flex justify-content-between align-items-center mb-3">
                    <h5 className="mb-0">
                      <i className="ph-clock me-2"></i>
                      Recent Login Sessions
                    </h5>
                    {failedLogins > 0 && (
                      <span className="badge bg-danger">
                        {failedLogins} failed attempt{failedLogins > 1 ? "s" : ""}
                      </span>
                    )}
                  </div>
                  <div className="table-responsive">
                    <table className="table">
                      <thead>
                        <tr>
                          <th>Time</th>
                          <th>Device</th>
                          <th>IP Address</th>
                          <th>Location</th>
                          <th>Status</th>
                        </tr>
                      </thead>
                      <tbody>
                        {sessions.map((session) => (
                          <tr key={session.id}>
                            <td>
                              <span className="fw-medium">{formatDateTime(session.loginTime)}</span>
                              <small className="d-block text-muted">{formatRelativeTime(session.loginTime)}</small>
                            </td>
                            <td>
                              <i className="ph-device-mobile me-1"></i>
                              {session.device}
                            </td>
                            <td>
                              <code>{session.ipAddress}</code>
                            </td>
                            <td>{session.location}</td>
                            <td>
                              {session.status === "success" ? (
                                <span className="badge bg-success bg-opacity-10 text-success">
                                  <i className="ph-check me-1"></i>
                                  Success
                                </span>
                              ) : (
                                <span className="badge bg-danger bg-opacity-10 text-danger">
                                  <i className="ph-x me-1"></i>
                                  Failed
                                </span>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </>
              )}

              {/* Security Log Tab */}
              {activeTab === "log" && (
                <>
                  <h5 className="mb-3">
                    <i className="ph-list-bullets me-2"></i>
                    Security Events
                  </h5>
                  <div className="timeline">
                    {securityEventsList.map((event) => (
                      <div key={event.id} className="d-flex mb-3">
                        <div className="me-3">
                          <div className={`bg-${event.color} bg-opacity-10 text-${event.color} rounded-pill p-2`}>
                            <i className={event.icon}></i>
                          </div>
                        </div>
                        <div className="flex-fill">
                          <div className="fw-medium">
                            {event.event} <span className="text-muted fw-normal">- {event.detail}</span>
                          </div>
                          <small className="text-muted">{formatRelativeTime(event.timestamp)}</small>
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="col-xl-4">
          {/* Security Status */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-shield me-2"></i>
                Security Status
              </h5>
            </div>
            <div className="card-body">
              <div className="d-flex align-items-center mb-3">
                <div className={`bg-${twoFactorEnabled ? "success" : "warning"} bg-opacity-10 text-${twoFactorEnabled ? "success" : "warning"} rounded-pill p-2 me-3`}>
                  <i className={`ph-${twoFactorEnabled ? "check" : "warning"}`}></i>
                </div>
                <div>
                  <div className="fw-medium">Two-Factor Auth</div>
                  <small className={twoFactorEnabled ? "text-success" : "text-warning"}>
                    {twoFactorEnabled ? "Enabled" : "Not enabled"}
                  </small>
                </div>
              </div>

              <div className="d-flex align-items-center mb-3">
                <div className="bg-success bg-opacity-10 text-success rounded-pill p-2 me-3">
                  <i className="ph-check"></i>
                </div>
                <div>
                  <div className="fw-medium">Password</div>
                  <small className="text-success">Set and active</small>
                </div>
              </div>

              <div className="d-flex align-items-center mb-3">
                <div className={`bg-${loginNotifications ? "success" : "warning"} bg-opacity-10 text-${loginNotifications ? "success" : "warning"} rounded-pill p-2 me-3`}>
                  <i className={`ph-${loginNotifications ? "check" : "warning"}`}></i>
                </div>
                <div>
                  <div className="fw-medium">Login Notifications</div>
                  <small className={loginNotifications ? "text-success" : "text-warning"}>
                    {loginNotifications ? "Enabled" : "Disabled"}
                  </small>
                </div>
              </div>

              <div className="d-flex align-items-center">
                <div className="bg-success bg-opacity-10 text-success rounded-pill p-2 me-3">
                  <i className="ph-check"></i>
                </div>
                <div>
                  <div className="fw-medium">Active Sessions</div>
                  <small className="text-success">
                    {activeSessionCount} active session{activeSessionCount !== 1 ? "s" : ""}
                  </small>
                </div>
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-lightning me-2"></i>
                Quick Actions
              </h5>
            </div>
            <div className="card-body">
              <div className="d-grid gap-2">
                <button className="btn btn-light text-start">
                  <i className="ph-sign-out me-2"></i>
                  Sign Out All Devices
                </button>
                <button className="btn btn-light text-start">
                  <i className="ph-download me-2"></i>
                  Export Security Log
                </button>
                <Link href="/account/privacy" className="btn btn-light text-start">
                  <i className="ph-lock-key me-2"></i>
                  Privacy Settings
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
