"use client";

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

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

interface ActivityItem {
  id: string;
  action: string;
  target: string;
  timestamp: Date;
  icon: string;
  color: string;
}

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

interface SerializedActivityItem {
  id: string;
  action: string;
  target: string;
  timestamp: string;
  icon: string;
  color: string;
}

interface UserAnalyticsProps {
  userName: string;
  userEmail: string;
  loginSessions?: SerializedLoginSession[];
  recentActivity?: SerializedActivityItem[];
  memberSince?: string | null;
  twoFactorEnabled?: boolean;
  activeSessionCount?: number;
}

export default function UserAnalytics({
  userName,
  userEmail,
  loginSessions: propLoginSessions,
  recentActivity: propRecentActivity,
  memberSince: propMemberSince,
  twoFactorEnabled = false,
  activeSessionCount = 0,
}: UserAnalyticsProps) {
  const [dateRange, setDateRange] = useState("30d");
  const [activeTab, setActiveTab] = useState<"overview" | "logins" | "activity">("overview");

  const memberSince = propMemberSince ? new Date(propMemberSince) : new Date();

  // Convert serialized data to Date objects
  const loginSessionsData: LoginSession[] = (propLoginSessions ?? []).map((s) => ({
    ...s,
    loginTime: new Date(s.loginTime),
  }));

  const recentActivityData: ActivityItem[] = (propRecentActivity ?? []).map((a) => ({
    ...a,
    timestamp: new Date(a.timestamp),
  }));

  const formatDate = (date: Date) => {
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  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 formatDate(date);
  };

  const totalLogins = loginSessionsData.filter((s) => s.status === "success").length;
  const failedLogins = loginSessionsData.filter((s) => s.status === "failed").length;
  const uniqueDevices = new Set(loginSessionsData.map((s) => s.device)).size;
  const daysSinceMember = Math.floor((Date.now() - memberSince.getTime()) / 86400000);

  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-chart-line-up me-2"></i>
              My Analytics
            </h4>
            <p className="text-muted mb-0 mt-1">View your account activity, usage statistics, and login history.</p>
          </div>
        </div>
        <select
          className="form-select"
          style={{ width: "auto" }}
          value={dateRange}
          onChange={(e) => setDateRange(e.target.value)}
        >
          <option value="7d">Last 7 days</option>
          <option value="30d">Last 30 days</option>
          <option value="90d">Last 90 days</option>
          <option value="1y">Last year</option>
        </select>
      </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">{totalLogins}</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">{uniqueDevices}</h4>
                <span className="text-muted">Devices Used</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">{recentActivityData.length}</h4>
                <span className="text-muted">Recent Actions</span>
              </div>
              <i className="ph-activity ph-2x text-info 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">{daysSinceMember}</h4>
                <span className="text-muted">Days as Member</span>
              </div>
              <i className="ph-calendar-check ph-2x text-warning opacity-75"></i>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="row">
        {/* Left Column */}
        <div className="col-xl-8">
          <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-chart-pie me-2"></i>
                    Overview
                  </button>
                </li>
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "logins" ? "active" : ""}`}
                    onClick={() => setActiveTab("logins")}
                  >
                    <i className="ph-sign-in me-2"></i>
                    Login History
                  </button>
                </li>
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "activity" ? "active" : ""}`}
                    onClick={() => setActiveTab("activity")}
                  >
                    <i className="ph-clock-counter-clockwise me-2"></i>
                    Activity Log
                  </button>
                </li>
              </ul>
            </div>

            <div className="card-body">
              {/* Overview Tab */}
              {activeTab === "overview" && (
                <>
                  <h5 className="mb-3">
                    <i className="ph-chart-bar me-2"></i>
                    Login Summary
                  </h5>
                  <div className="row mb-4">
                    <div className="col-md-4">
                      <div className="card bg-light border-0">
                        <div className="card-body text-center">
                          <h3 className="mb-1 text-success">{totalLogins}</h3>
                          <small className="text-muted">Successful Logins</small>
                        </div>
                      </div>
                    </div>
                    <div className="col-md-4">
                      <div className="card bg-light border-0">
                        <div className="card-body text-center">
                          <h3 className={`mb-1 ${failedLogins > 0 ? "text-danger" : ""}`}>{failedLogins}</h3>
                          <small className="text-muted">Failed Attempts</small>
                        </div>
                      </div>
                    </div>
                    <div className="col-md-4">
                      <div className="card bg-light border-0">
                        <div className="card-body text-center">
                          <h3 className="mb-1 text-primary">{uniqueDevices}</h3>
                          <small className="text-muted">Unique Devices</small>
                        </div>
                      </div>
                    </div>
                  </div>

                  {loginSessionsData.length > 0 && (
                    <>
                      <h5 className="mb-3">
                        <i className="ph-clock me-2"></i>
                        Latest Logins
                      </h5>
                      <div className="table-responsive">
                        <table className="table table-hover">
                          <thead>
                            <tr>
                              <th>Time</th>
                              <th>Device</th>
                              <th>IP Address</th>
                              <th>Status</th>
                            </tr>
                          </thead>
                          <tbody>
                            {loginSessionsData.slice(0, 5).map((session) => (
                              <tr key={session.id}>
                                <td>{formatRelativeTime(session.loginTime)}</td>
                                <td>{session.device}</td>
                                <td><code>{session.ipAddress}</code></td>
                                <td>
                                  <span className={`badge bg-${session.status === "success" ? "success" : "danger"} bg-opacity-10 text-${session.status === "success" ? "success" : "danger"}`}>
                                    {session.status === "success" ? "Success" : "Failed"}
                                  </span>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </>
                  )}

                  {loginSessionsData.length === 0 && recentActivityData.length === 0 && (
                    <div className="text-center text-muted py-4">
                      <i className="ph-chart-line-up fs-1 d-block mb-2 opacity-50"></i>
                      <p className="mb-0">No activity data available yet.</p>
                    </div>
                  )}
                </>
              )}

              {/* Login History Tab */}
              {activeTab === "logins" && (
                <>
                  <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>
                        {loginSessionsData.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>
                </>
              )}

              {/* Activity Log Tab */}
              {activeTab === "activity" && (
                <>
                  <h5 className="mb-3">
                    <i className="ph-list-bullets me-2"></i>
                    Recent Activity
                  </h5>
                  <div className="timeline">
                    {recentActivityData.map((activity) => (
                      <div key={activity.id} className="d-flex mb-3">
                        <div className="me-3">
                          <div className={`bg-${activity.color} bg-opacity-10 text-${activity.color} rounded-pill p-2`}>
                            <i className={activity.icon}></i>
                          </div>
                        </div>
                        <div className="flex-fill">
                          <div className="fw-medium">
                            {activity.action} <span className="text-primary">{activity.target}</span>
                          </div>
                          <small className="text-muted">{formatRelativeTime(activity.timestamp)}</small>
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="col-xl-4">
          {/* Account Info Card */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-user me-2"></i>
                Account Information
              </h5>
            </div>
            <div className="card-body">
              <div className="text-center mb-4">
                <div
                  className="bg-primary bg-opacity-10 text-primary rounded-circle d-inline-flex align-items-center justify-content-center"
                  style={{ width: "80px", height: "80px" }}
                >
                  <i className="ph-user ph-2x"></i>
                </div>
                <h5 className="mt-3 mb-0">{userName}</h5>
                <p className="text-muted">{userEmail}</p>
              </div>

              <div className="list-group list-group-flush">
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Member since</span>
                  <span className="fw-medium">{formatDate(memberSince)}</span>
                </div>
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Total logins</span>
                  <span className="fw-medium">{totalLogins}</span>
                </div>
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Failed attempts</span>
                  <span className={`fw-medium ${failedLogins > 0 ? "text-danger" : ""}`}>{failedLogins}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Security Status Card */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-shield-check 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 Authentication</div>
                  <small className={twoFactorEnabled ? "text-success" : "text-warning"}>
                    {twoFactorEnabled ? "Enabled" : "Not enabled"}
                  </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 className="card-footer">
              <Link href="/security" className="btn btn-outline-primary btn-sm w-100">
                <i className="ph-gear me-2"></i>
                Manage Security Settings
              </Link>
            </div>
          </div>

          {/* Quick Actions Card */}
          <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-download me-2"></i>
                  Export Activity Log
                </button>
                <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-trash me-2"></i>
                  Clear Activity History
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
