/**
 * Secrets Hierarchy Visualization - Phase 3.3
 *
 * Displays workspace → domain → secret hierarchy with filtering,
 * rotation status, and sharing information.
 */

import React, { useState, useEffect } from 'react';
import { ChevronDown, ChevronRight, Lock, Clock, Share2, AlertCircle } from 'lucide-react';

interface Secret {
  id: string;
  path: string;
  type: 'database' | 'application' | 'ssh' | 'provider';
  lifecycle: 'temporal' | 'permanent';
  createdAt: string;
  rotationSchedule?: {
    nextRotation: string;
    lastRotation?: string;
    status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'disabled';
  };
  sharedWith?: {
    workspace: string;
    permission: 'read' | 'read_write' | 'rotate';
    grantedAt: string;
  }[];
  accessCount?: number;
  lastAccessed?: string;
}

interface Domain {
  name: string;
  secrets: Secret[];
  expanded?: boolean;
}

interface Infrastructure {
  name: string;
  domains: Domain[];
  expanded?: boolean;
}

interface Workspace {
  id: string;
  name: string;
  infrastructures: Infrastructure[];
  expanded?: boolean;
}

interface SecretsHierarchyProps {
  workspaces: Workspace[];
  onSecretSelect: (secret: Secret) => void;
  onRotateSecret?: (secret: Secret) => void;
  onShareSecret?: (secret: Secret) => void;
}

/**
 * Secret type badge with color coding
 */
const SecretTypeBadge: React.FC<{ type: Secret['type'] }> = ({ type }) => {
  const colors: Record<Secret['type'], string> = {
    database: 'bg-blue-100 text-blue-800',
    application: 'bg-green-100 text-green-800',
    ssh: 'bg-purple-100 text-purple-800',
    provider: 'bg-orange-100 text-orange-800',
  };

  const labels: Record<Secret['type'], string> = {
    database: 'DB',
    application: 'App',
    ssh: 'SSH',
    provider: 'Provider',
  };

  return (
    <span className={`px-2 py-1 rounded-full text-xs font-semibold ${colors[type]}`}>
      {labels[type]}
    </span>
  );
};

/**
 * Rotation status indicator
 */
const RotationStatus: React.FC<{ schedule: Secret['rotationSchedule'] }> = ({ schedule }) => {
  if (!schedule) return null;

  const statusColors: Record<string, string> = {
    pending: 'text-yellow-600 bg-yellow-50',
    in_progress: 'text-blue-600 bg-blue-50',
    completed: 'text-green-600 bg-green-50',
    failed: 'text-red-600 bg-red-50',
    disabled: 'text-gray-600 bg-gray-50',
  };

  const statusIcons: Record<string, React.ReactNode> = {
    pending: <Clock size={16} className="mr-1" />,
    in_progress: <Clock size={16} className="mr-1 animate-spin" />,
    completed: <Lock size={16} className="mr-1" />,
    failed: <AlertCircle size={16} className="mr-1" />,
    disabled: <Lock size={16} className="mr-1 opacity-50" />,
  };

  const nextRotationDate = new Date(schedule.nextRotation);
  const today = new Date();
  const daysUntilRotation = Math.ceil(
    (nextRotationDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)
  );

  return (
    <div className={`flex items-center text-xs px-2 py-1 rounded ${statusColors[schedule.status]}`}>
      {statusIcons[schedule.status]}
      <span className="font-medium">
        {schedule.status === 'pending'
          ? `Rotate in ${daysUntilRotation} days`
          : schedule.status === 'completed'
          ? `Last: ${new Date(schedule.lastRotation!).toLocaleDateString()}`
          : schedule.status}
      </span>
    </div>
  );
};

/**
 * Sharing indicator with count
 */
const SharingIndicator: React.FC<{ sharedWith?: Secret['sharedWith'] }> = ({ sharedWith }) => {
  if (!sharedWith || sharedWith.length === 0) return null;

  return (
    <div className="flex items-center text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded">
      <Share2 size={14} className="mr-1" />
      <span className="font-medium">Shared with {sharedWith.length} workspace(s)</span>
    </div>
  );
};

/**
 * Secret item row
 */
const SecretItem: React.FC<{
  secret: Secret;
  onSelect: (secret: Secret) => void;
  onRotate?: (secret: Secret) => void;
  onShare?: (secret: Secret) => void;
}> = ({ secret, onSelect, onRotate, onShare }) => {
  const secretName = secret.path.split('/').pop() || secret.path;

  return (
    <div className="pl-8 py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors">
      <div className="flex items-center justify-between">
        <div className="flex-1 flex items-center gap-3">
          <Lock size={16} className="text-gray-400" />
          <div className="flex-1">
            <div
              className="font-medium text-sm cursor-pointer text-gray-900 hover:text-blue-600"
              onClick={() => onSelect(secret)}
            >
              {secretName}
            </div>
            <div className="text-xs text-gray-500 mt-1">
              Created: {new Date(secret.createdAt).toLocaleDateString()}
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2 ml-4">
          <SecretTypeBadge type={secret.type} />

          {secret.lifecycle === 'temporary' && (
            <span className="px-2 py-1 rounded-full text-xs font-semibold bg-yellow-100 text-yellow-800">
              Temporal
            </span>
          )}

          {secret.rotationSchedule && <RotationStatus schedule={secret.rotationSchedule} />}

          <SharingIndicator sharedWith={secret.sharedWith} />

          <div className="text-xs text-gray-600">
            {secret.accessCount !== undefined && `Accessed ${secret.accessCount}x`}
          </div>

          <div className="flex items-center gap-1">
            {onRotate && secret.rotationSchedule && (
              <button
                onClick={() => onRotate(secret)}
                className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
              >
                Rotate
              </button>
            )}
            {onShare && (
              <button
                onClick={() => onShare(secret)}
                className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
              >
                Share
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * Domain section with expandable secrets list
 */
const DomainSection: React.FC<{
  domain: Domain;
  infrastructure: string;
  workspace: string;
  expanded: boolean;
  onToggle: () => void;
  onSecretSelect: (secret: Secret) => void;
  onRotateSecret?: (secret: Secret) => void;
  onShareSecret?: (secret: Secret) => void;
}> = ({
  domain,
  infrastructure,
  workspace,
  expanded,
  onToggle,
  onSecretSelect,
  onRotateSecret,
  onShareSecret,
}) => {
  return (
    <div className="pl-4">
      <button
        onClick={onToggle}
        className="w-full text-left py-2 px-4 flex items-center gap-2 hover:bg-gray-50 transition-colors"
      >
        {expanded ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
        <span className="font-semibold text-sm text-gray-700">{domain.name}</span>
        <span className="text-xs text-gray-500 ml-auto">
          {domain.secrets.length} secret{domain.secrets.length !== 1 ? 's' : ''}
        </span>
      </button>

      {expanded && (
        <div className="border-l-2 border-gray-200">
          {domain.secrets.length === 0 ? (
            <div className="pl-8 py-3 text-xs text-gray-500 italic">No secrets</div>
          ) : (
            domain.secrets.map((secret) => (
              <SecretItem
                key={secret.id}
                secret={secret}
                onSelect={onSecretSelect}
                onRotate={onRotateSecret}
                onShare={onShareSecret}
              />
            ))
          )}
        </div>
      )}
    </div>
  );
};

/**
 * Infrastructure section
 */
const InfrastructureSection: React.FC<{
  infrastructure: Infrastructure;
  workspace: string;
  expanded: boolean;
  onToggle: () => void;
  onSecretSelect: (secret: Secret) => void;
  onRotateSecret?: (secret: Secret) => void;
  onShareSecret?: (secret: Secret) => void;
  domainExpandedState: Record<string, boolean>;
  onDomainToggle: (domain: string) => void;
}> = ({
  infrastructure,
  workspace,
  expanded,
  onToggle,
  onSecretSelect,
  onRotateSecret,
  onShareSecret,
  domainExpandedState,
  onDomainToggle,
}) => {
  return (
    <div className="pl-2">
      <button
        onClick={onToggle}
        className="w-full text-left py-2 px-4 flex items-center gap-2 hover:bg-gray-50 transition-colors"
      >
        {expanded ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
        <span className="font-semibold text-gray-800">{infrastructure.name}</span>
        <span className="text-xs text-gray-500 ml-auto">
          {infrastructure.domains.reduce((acc, d) => acc + d.secrets.length, 0)} secrets
        </span>
      </button>

      {expanded && (
        <div>
          {infrastructure.domains.map((domain) => {
            const domainKey = `${workspace}/${infrastructure.name}/${domain.name}`;
            const isExpanded = domainExpandedState[domainKey] || false;

            return (
              <DomainSection
                key={domainKey}
                domain={domain}
                infrastructure={infrastructure.name}
                workspace={workspace}
                expanded={isExpanded}
                onToggle={() => onDomainToggle(domainKey)}
                onSecretSelect={onSecretSelect}
                onRotateSecret={onRotateSecret}
                onShareSecret={onShareSecret}
              />
            );
          })}
        </div>
      )}
    </div>
  );
};

/**
 * Main Workspace section
 */
const WorkspaceSection: React.FC<{
  workspace: Workspace;
  expanded: boolean;
  onToggle: () => void;
  onSecretSelect: (secret: Secret) => void;
  onRotateSecret?: (secret: Secret) => void;
  onShareSecret?: (secret: Secret) => void;
  infraExpandedState: Record<string, boolean>;
  onInfraToggle: (infra: string) => void;
  domainExpandedState: Record<string, boolean>;
  onDomainToggle: (domain: string) => void;
}> = ({
  workspace,
  expanded,
  onToggle,
  onSecretSelect,
  onRotateSecret,
  onShareSecret,
  infraExpandedState,
  onInfraToggle,
  domainExpandedState,
  onDomainToggle,
}) => {
  return (
    <div className="border-b border-gray-200">
      <button
        onClick={onToggle}
        className="w-full text-left py-3 px-4 flex items-center gap-2 hover:bg-gray-50 transition-colors bg-gray-50"
      >
        {expanded ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
        <span className="font-bold text-lg text-gray-900">{workspace.name}</span>
        <span className="text-sm text-gray-500 ml-auto">
          {workspace.infrastructures.reduce(
            (acc, i) => acc + i.domains.reduce((d, dom) => d + dom.secrets.length, 0),
            0
          )}{' '}
          secrets
        </span>
      </button>

      {expanded && (
        <div className="bg-white">
          {workspace.infrastructures.length === 0 ? (
            <div className="pl-4 py-3 text-sm text-gray-500 italic">No infrastructures</div>
          ) : (
            workspace.infrastructures.map((infra) => {
              const infraKey = `${workspace.id}/${infra.name}`;
              const isExpanded = infraExpandedState[infraKey] || false;

              return (
                <InfrastructureSection
                  key={infraKey}
                  infrastructure={infra}
                  workspace={workspace.id}
                  expanded={isExpanded}
                  onToggle={() => onInfraToggle(infraKey)}
                  onSecretSelect={onSecretSelect}
                  onRotateSecret={onRotateSecret}
                  onShareSecret={onShareSecret}
                  domainExpandedState={domainExpandedState}
                  onDomainToggle={onDomainToggle}
                />
              );
            })
          )}
        </div>
      )}
    </div>
  );
};

/**
 * Main Secrets Hierarchy Component
 */
export const SecretsHierarchy: React.FC<SecretsHierarchyProps> = ({
  workspaces,
  onSecretSelect,
  onRotateSecret,
  onShareSecret,
}) => {
  const [workspaceExpandedState, setWorkspaceExpandedState] = useState<Record<string, boolean>>({});
  const [infraExpandedState, setInfraExpandedState] = useState<Record<string, boolean>>({});
  const [domainExpandedState, setDomainExpandedState] = useState<Record<string, boolean>>({});

  const toggleWorkspace = (workspaceId: string) => {
    setWorkspaceExpandedState((prev) => ({
      ...prev,
      [workspaceId]: !prev[workspaceId],
    }));
  };

  const toggleInfra = (infraKey: string) => {
    setInfraExpandedState((prev) => ({
      ...prev,
      [infraKey]: !prev[infraKey],
    }));
  };

  const toggleDomain = (domainKey: string) => {
    setDomainExpandedState((prev) => ({
      ...prev,
      [domainKey]: !prev[domainKey],
    }));
  };

  return (
    <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
      <div className="bg-gray-100 px-4 py-3 border-b border-gray-200">
        <h2 className="text-lg font-bold text-gray-900">Secrets Management</h2>
        <p className="text-sm text-gray-600 mt-1">
          Manage temporal and permanent secrets across workspaces
        </p>
      </div>

      <div className="divide-y divide-gray-200 max-h-96 overflow-y-auto">
        {workspaces.length === 0 ? (
          <div className="p-4 text-center text-gray-500">
            <p className="text-sm">No workspaces found</p>
          </div>
        ) : (
          workspaces.map((workspace) => {
            const isExpanded = workspaceExpandedState[workspace.id] || false;

            return (
              <WorkspaceSection
                key={workspace.id}
                workspace={workspace}
                expanded={isExpanded}
                onToggle={() => toggleWorkspace(workspace.id)}
                onSecretSelect={onSecretSelect}
                onRotateSecret={onRotateSecret}
                onShareSecret={onShareSecret}
                infraExpandedState={infraExpandedState}
                onInfraToggle={toggleInfra}
                domainExpandedState={domainExpandedState}
                onDomainToggle={toggleDomain}
              />
            );
          })
        )}
      </div>
    </div>
  );
};

export default SecretsHierarchy;
