"use client";

import { Clock, Copy, Check, Users, Building2 } from "lucide-react";
import { UserData, LoginHistoryEntry } from "./types";

interface OverviewTabProps {
  user: UserData;
  userDetails: Record<string, unknown> | null;
  loginHistory: LoginHistoryEntry[];
  copiedText: string | null;
  onCopyToClipboard: (text: string) => void;
  onNavigateToHistory: () => void;
}

export function OverviewTab({
  user,
  userDetails,
  loginHistory,
  copiedText,
  onCopyToClipboard,
  onNavigateToHistory,
}: OverviewTabProps) {
  const isTeamMember = Boolean(userDetails?.isTeamMember);

  return (
    <div className="space-y-6">
      {/* Account Status Section */}
      <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
        <h4 className="font-semibold text-brand-ink mb-3">Account Status</h4>
        <div
          className={`grid ${isTeamMember ? "grid-cols-1" : "grid-cols-3"} gap-4`}
        >
          <div>
            <label className="block text-xs text-gray-600 uppercase mb-1">
              Status
            </label>
            <span
              className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                user.status === "active"
                  ? "bg-green-100 text-green-800"
                  : user.status === "suspended"
                    ? "bg-orange-100 text-orange-800"
                    : "bg-red-100 text-red-800"
              }`}
            >
              {user.status}
            </span>
          </div>
          {/* Hide Email Verified and Onboarding for team members */}
          {!isTeamMember && (
            <>
              <div>
                <label className="block text-xs text-gray-600 uppercase mb-1">
                  Email Verified
                </label>
                <p className="text-base">
                  {Boolean(userDetails?.emailVerified) ? "Yes" : "No"}
                </p>
              </div>
              <div>
                <label className="block text-xs text-gray-600 uppercase mb-1">
                  Onboarding
                </label>
                <p className="text-base">
                  {Boolean(userDetails?.onboardingComplete)
                    ? "Complete"
                    : "Incomplete"}
                </p>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Personal Information */}
      <div>
        <h4 className="font-semibold text-brand-ink mb-3">
          Personal Information
        </h4>
        <div className="grid grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Name
            </label>
            <p className="text-base text-gray-900">{user.name}</p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Email
            </label>
            <div className="flex items-center gap-2">
              <p className="text-base text-gray-900">{user.email}</p>
              <button onClick={() => onCopyToClipboard(user.email)}>
                {copiedText === user.email ? (
                  <Check className="w-4 h-4 text-green-600" />
                ) : (
                  <Copy className="w-4 h-4 text-gray-400 hover:text-gray-600" />
                )}
              </button>
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Phone Number
            </label>
            <p className="text-base text-gray-900">
              {(userDetails?.phoneNumber as string) || "-"}
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Role
            </label>
            {isTeamMember && userDetails?.teamMembership ? (
              <div>
                <span className="inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full bg-blue-100 text-blue-800">
                  <Users className="w-3.5 h-3.5" />
                  Staff Member
                </span>
                <p className="text-sm text-gray-600 mt-1">
                  at{" "}
                  <span className="font-medium">
                    {String(
                      (
                        userDetails.teamMembership as {
                          organizationName: string;
                        }
                      )?.organizationName || "",
                    )}
                  </span>
                </p>
              </div>
            ) : Boolean(userDetails?.isOrgOwner) &&
              userDetails?.ownedOrganization ? (
              <div>
                <span className="inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full bg-emerald-100 text-emerald-800">
                  <Building2 className="w-3.5 h-3.5" />
                  Company Owner
                </span>
                <p className="text-sm text-gray-600 mt-1">
                  of{" "}
                  <span className="font-medium">
                    {String(
                      (userDetails.ownedOrganization as { name: string })
                        ?.name || "",
                    )}
                  </span>
                </p>
              </div>
            ) : (
              <p className="text-base text-gray-900">{user.role}</p>
            )}
          </div>
        </div>
      </div>

      {/* Team Membership Section - Only for team members */}
      {isTeamMember && Boolean(userDetails?.teamMembership) && (
        <TeamMembershipSection
          teamMembership={userDetails!.teamMembership as TeamMembership}
        />
      )}

      {/* Company Owner Section - Only for organization owners */}
      {Boolean(userDetails?.isOrgOwner) &&
        Boolean(userDetails?.ownedOrganization) && (
          <CompanyOwnerSection
            ownedOrganization={
              userDetails!.ownedOrganization as OwnedOrganization
            }
          />
        )}

      {/* Company Information - Only for non-team-members */}
      {!isTeamMember && (
        <div>
          <h4 className="font-semibold text-brand-ink mb-3">
            Company Information
          </h4>
          <div className="grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Company Name
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.companyName as string) ||
                  user.companyName ||
                  "-"}
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Industry
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.industry as string) || user.industry || "-"}
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Company Size
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.companySize as string) || "-"}
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Website
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.website as string) || "-"}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Location Information - Only for non-team-members */}
      {!isTeamMember && (
        <div>
          <h4 className="font-semibold text-brand-ink mb-3">Location</h4>
          <div className="grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Country
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.country as string) || user.country || "-"}
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                City
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.city as string) || user.city || "-"}
              </p>
            </div>
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Address
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.address as string) || "-"}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Account Activity */}
      <div>
        <h4 className="font-semibold text-brand-ink mb-3">Account Activity</h4>
        <div className="grid grid-cols-3 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {isTeamMember ? "Added to Team" : "Registered"}
            </label>
            <p className="text-base text-gray-900">
              {new Date(user.createdAt).toLocaleDateString()}
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Last Login
            </label>
            <p className="text-base text-gray-900">
              {user.lastLoginAt
                ? new Date(user.lastLoginAt).toLocaleDateString()
                : "Never"}
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Login Count
            </label>
            <p className="text-base text-gray-900">{user.loginCount}</p>
          </div>
        </div>
      </div>

      {/* Session Activity Summary */}
      {loginHistory.length > 0 && (
        <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
          <h4 className="font-semibold text-brand-ink mb-3 flex items-center gap-2">
            <Clock className="w-4 h-4" />
            Session Activity
          </h4>
          <div className="grid grid-cols-4 gap-4">
            <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
              <div className="text-2xl font-bold text-green-600">
                {loginHistory.filter((l) => l.success && !l.logoutAt).length}
              </div>
              <div className="text-xs text-gray-600 mt-1">Active Sessions</div>
            </div>
            <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
              <div className="text-2xl font-bold text-blue-600">
                {loginHistory.filter((l) => l.success).length}
              </div>
              <div className="text-xs text-gray-600 mt-1">
                Successful Logins
              </div>
            </div>
            <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
              <div className="text-2xl font-bold text-red-600">
                {loginHistory.filter((l) => !l.success).length}
              </div>
              <div className="text-xs text-gray-600 mt-1">Failed Attempts</div>
            </div>
            <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
              <div className="text-2xl font-bold text-gray-600">
                {
                  new Set(loginHistory.map((l) => l.country).filter(Boolean))
                    .size
                }
              </div>
              <div className="text-xs text-gray-600 mt-1">Countries</div>
            </div>
          </div>
          <button
            onClick={onNavigateToHistory}
            className="mt-3 text-sm text-blue-600 hover:text-blue-800 font-medium"
          >
            View Full Session History
          </button>
        </div>
      )}

      {/* Subscription & Billing - Only for non-team-members */}
      {!isTeamMember && (
        <div>
          <h4 className="font-semibold text-brand-ink mb-3">Subscription</h4>
          <div className="grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Selected Package
              </label>
              <p className="text-base text-gray-900">
                {(userDetails?.selectedPackage as string) || "-"}
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Stripe Customer
              </label>
              <p className="text-base text-gray-900">
                {userDetails?.stripeCustomerId ? "Connected" : "Not connected"}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Internal types for this component
interface TeamMembership {
  organizationName: string;
  role: string;
  owner?: { name: string; email: string };
  joinedAt?: string;
}

interface OwnedOrganization {
  name: string;
  memberCount: number;
}

// Sub-components
function TeamMembershipSection({
  teamMembership,
}: {
  teamMembership: TeamMembership;
}) {
  return (
    <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
      <div className="flex items-center gap-3 mb-4">
        <div className="p-2 bg-blue-100 rounded-lg">
          <Users className="w-5 h-5 text-blue-600" />
        </div>
        <div>
          <h4 className="font-semibold text-brand-ink">Team Member</h4>
          <p className="text-sm text-gray-600">
            This user is part of another organization&apos;s team
          </p>
        </div>
      </div>
      <div className="grid grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Organization
          </label>
          <div className="flex items-center gap-2">
            <Building2 className="w-4 h-4 text-gray-400" />
            <p className="text-base font-medium text-gray-900">
              {teamMembership.organizationName}
            </p>
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Team Role
          </label>
          <span
            className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
              teamMembership.role === "ADMIN"
                ? "bg-purple-100 text-purple-800"
                : teamMembership.role === "MEMBER"
                  ? "bg-blue-100 text-blue-800"
                  : "bg-gray-100 text-gray-800"
            }`}
          >
            {teamMembership.role}
          </span>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Organization Owner
          </label>
          <div>
            <p className="text-base text-gray-900">
              {teamMembership.owner?.name || "-"}
            </p>
            <p className="text-xs text-gray-500">
              {teamMembership.owner?.email || ""}
            </p>
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Joined Team
          </label>
          <p className="text-base text-gray-900">
            {teamMembership.joinedAt
              ? new Date(teamMembership.joinedAt).toLocaleDateString()
              : "-"}
          </p>
        </div>
      </div>
      <div className="mt-4 p-3 bg-blue-100 border border-blue-200 rounded-lg">
        <p className="text-sm text-blue-800">
          <strong>Note:</strong> Team members do not have their own subscription
          or company profile. They access the platform through their team
          organization&apos;s subscription.
        </p>
      </div>
    </div>
  );
}

function CompanyOwnerSection({
  ownedOrganization,
}: {
  ownedOrganization: OwnedOrganization;
}) {
  return (
    <div className="p-4 bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 rounded-lg">
      <div className="flex items-center gap-3 mb-4">
        <div className="p-2 bg-emerald-100 rounded-lg">
          <Building2 className="w-5 h-5 text-emerald-600" />
        </div>
        <div>
          <h4 className="font-semibold text-brand-ink">Company Owner</h4>
          <p className="text-sm text-gray-600">
            This user owns an organization
          </p>
        </div>
      </div>
      <div className="grid grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Organization
          </label>
          <div className="flex items-center gap-2">
            <Building2 className="w-4 h-4 text-gray-400" />
            <p className="text-base font-medium text-gray-900">
              {ownedOrganization.name}
            </p>
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Team Members
          </label>
          <div className="flex items-center gap-2">
            <Users className="w-4 h-4 text-gray-400" />
            <p className="text-base text-gray-900">
              {ownedOrganization.memberCount} members
            </p>
          </div>
        </div>
      </div>
      <div className="mt-4 p-3 bg-emerald-100 border border-emerald-200 rounded-lg">
        <p className="text-sm text-emerald-800">
          <strong>Owner Privileges:</strong> Full access to billing, team
          management, and all organization features.
        </p>
      </div>
    </div>
  );
}
