import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Stats, DeduplicationStats, ReferencedArtifact } from '../types';
import { getStats, getDeduplicationStats } from '../api';
import { DataTable } from '../components/DataTable';
import './Dashboard.css';

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}

function formatNumber(num: number): string {
  return num.toLocaleString();
}

function truncateHash(hash: string, length: number = 12): string {
  if (hash.length <= length) return hash;
  return `${hash.slice(0, length)}...`;
}

interface StatCardProps {
  label: string;
  value: string;
  subvalue?: string;
  icon: React.ReactNode;
  variant?: 'default' | 'success' | 'accent';
  trend?: 'up' | 'down' | 'neutral';
}

function StatCard({ label, value, subvalue, icon, variant = 'default', trend }: StatCardProps) {
  return (
    <div className={`stat-card stat-card--${variant}`}>
      <div className="stat-card__icon">{icon}</div>
      <div className="stat-card__content">
        <span className="stat-card__label">{label}</span>
        <span className="stat-card__value">
          {value}
          {trend && (
            <span className={`stat-card__trend stat-card__trend--${trend}`}>
              {trend === 'up' && '↑'}
              {trend === 'down' && '↓'}
            </span>
          )}
        </span>
        {subvalue && <span className="stat-card__subvalue">{subvalue}</span>}
      </div>
    </div>
  );
}

interface ProgressBarProps {
  value: number;
  max: number;
  label?: string;
  showPercentage?: boolean;
  variant?: 'default' | 'success' | 'accent';
}

function ProgressBar({ value, max, label, showPercentage = true, variant = 'default' }: ProgressBarProps) {
  const percentage = max > 0 ? Math.min((value / max) * 100, 100) : 0;
  
  return (
    <div className={`progress-bar progress-bar--${variant}`}>
      {label && (
        <div className="progress-bar__header">
          <span className="progress-bar__label">{label}</span>
          {showPercentage && <span className="progress-bar__percentage">{percentage.toFixed(1)}%</span>}
        </div>
      )}
      <div className="progress-bar__track">
        <div 
          className="progress-bar__fill" 
          style={{ width: `${percentage}%` }}
        />
        <div className="progress-bar__glow" style={{ width: `${percentage}%` }} />
      </div>
    </div>
  );
}

function Dashboard() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [dedupStats, setDedupStats] = useState<DeduplicationStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadStats() {
      try {
        setLoading(true);
        const [statsData, dedupData] = await Promise.all([
          getStats(),
          getDeduplicationStats(),
        ]);
        setStats(statsData);
        setDedupStats(dedupData);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load statistics');
      } finally {
        setLoading(false);
      }
    }
    loadStats();
  }, []);

  if (loading) {
    return (
      <div className="dashboard">
        <div className="dashboard__loading">
          <div className="dashboard__loading-spinner" />
          <span>Loading statistics...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="dashboard">
        <div className="dashboard__error">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <circle cx="12" cy="12" r="10"/>
            <line x1="12" y1="8" x2="12" y2="12"/>
            <line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
          <h3>Unable to load dashboard</h3>
          <p>{error}</p>
          <button className="btn btn-primary" onClick={() => window.location.reload()}>
            Try Again
          </button>
        </div>
      </div>
    );
  }

  const artifactColumns = [
    {
      key: 'artifact_id',
      header: 'Artifact ID',
      render: (item: ReferencedArtifact) => (
        <Link to={`/artifact/${item.artifact_id}`} className="artifact-link">
          <code>{truncateHash(item.artifact_id, 16)}</code>
        </Link>
      ),
    },
    {
      key: 'original_name',
      header: 'Name',
      render: (item: ReferencedArtifact) => (
        <span className="artifact-name" title={item.original_name || 'Unknown'}>
          {item.original_name || '—'}
        </span>
      ),
    },
    {
      key: 'size',
      header: 'Size',
      render: (item: ReferencedArtifact) => formatBytes(item.size),
    },
    {
      key: 'ref_count',
      header: 'References',
      render: (item: ReferencedArtifact) => (
        <span className="ref-count">
          <span className="ref-count__value">{formatNumber(item.ref_count)}</span>
          <span className="ref-count__label">refs</span>
        </span>
      ),
    },
    {
      key: 'storage_saved',
      header: 'Storage Saved',
      render: (item: ReferencedArtifact) => (
        <span className="storage-saved">
          {formatBytes(item.storage_saved)}
        </span>
      ),
    },
  ];

  return (
    <div className="dashboard">
      <header className="dashboard__header">
        <div className="dashboard__header-content">
          <h1>Storage Dashboard</h1>
          <p className="dashboard__subtitle">Real-time deduplication and storage analytics</p>
        </div>
        <div className="dashboard__header-accent" />
      </header>

      <section className="dashboard__section">
        <h2 className="dashboard__section-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
          </svg>
          Storage Overview
        </h2>
        <div className="stat-grid stat-grid--4">
          <StatCard
            label="Total Storage Used"
            value={formatBytes(stats?.total_size_bytes || 0)}
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
              </svg>
            }
            variant="default"
          />
          <StatCard
            label="Storage Saved"
            value={formatBytes(stats?.storage_saved_bytes || 0)}
            subvalue="through deduplication"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/>
                <polyline points="17 6 23 6 23 12"/>
              </svg>
            }
            variant="success"
          />
          <StatCard
            label="Deduplication Ratio"
            value={`${(stats?.deduplication_ratio || 1).toFixed(2)}x`}
            subvalue="compression achieved"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                <line x1="3" y1="9" x2="21" y2="9"/>
                <line x1="9" y1="21" x2="9" y2="9"/>
              </svg>
            }
            variant="accent"
          />
          <StatCard
            label="Savings Percentage"
            value={`${(dedupStats?.savings_percentage || 0).toFixed(1)}%`}
            subvalue="of logical storage"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12 6 12 12 16 14"/>
              </svg>
            }
            variant="success"
          />
        </div>
      </section>

      <section className="dashboard__section">
        <h2 className="dashboard__section-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M12 20V10"/>
            <path d="M18 20V4"/>
            <path d="M6 20v-4"/>
          </svg>
          Artifact Statistics
        </h2>
        <div className="stat-grid stat-grid--4">
          <StatCard
            label="Total Artifacts"
            value={formatNumber(stats?.total_artifacts || 0)}
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
                <polyline points="14 2 14 8 20 8"/>
              </svg>
            }
          />
          <StatCard
            label="Total Uploads"
            value={formatNumber(stats?.total_uploads || 0)}
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="17 8 12 3 7 8"/>
                <line x1="12" y1="3" x2="12" y2="15"/>
              </svg>
            }
          />
          <StatCard
            label="Deduplicated Uploads"
            value={formatNumber(stats?.deduplicated_uploads || 0)}
            subvalue="uploads reusing existing"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
              </svg>
            }
            variant="success"
          />
          <StatCard
            label="Unique Artifacts"
            value={formatNumber(stats?.unique_artifacts || 0)}
            subvalue="distinct content hashes"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
              </svg>
            }
          />
        </div>
      </section>

      <section className="dashboard__section">
        <h2 className="dashboard__section-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="12" y1="20" x2="12" y2="10"/>
            <line x1="18" y1="20" x2="18" y2="4"/>
            <line x1="6" y1="20" x2="6" y2="16"/>
          </svg>
          Deduplication Effectiveness
        </h2>
        <div className="effectiveness-grid">
          <div className="effectiveness-card">
            <h3>Logical vs Physical Storage</h3>
            <div className="storage-comparison">
              <div className="storage-bar">
                <div className="storage-bar__label">
                  <span>Logical (with duplicates)</span>
                  <span className="storage-bar__value">{formatBytes(dedupStats?.total_logical_bytes || 0)}</span>
                </div>
                <ProgressBar 
                  value={dedupStats?.total_logical_bytes || 0} 
                  max={dedupStats?.total_logical_bytes || 1}
                  showPercentage={false}
                  variant="default"
                />
              </div>
              <div className="storage-bar">
                <div className="storage-bar__label">
                  <span>Physical (actual storage)</span>
                  <span className="storage-bar__value">{formatBytes(dedupStats?.total_physical_bytes || 0)}</span>
                </div>
                <ProgressBar 
                  value={dedupStats?.total_physical_bytes || 0} 
                  max={dedupStats?.total_logical_bytes || 1}
                  showPercentage={false}
                  variant="success"
                />
              </div>
            </div>
            <div className="storage-savings">
              <div className="storage-savings__icon">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </div>
              <div className="storage-savings__content">
                <span className="storage-savings__value">{formatBytes(dedupStats?.bytes_saved || 0)}</span>
                <span className="storage-savings__label">saved through deduplication</span>
              </div>
            </div>
          </div>

          <div className="effectiveness-card">
            <h3>Deduplication Rate</h3>
            <div className="dedup-rate">
              <div className="dedup-rate__circle">
                <svg viewBox="0 0 100 100" className="dedup-rate__svg">
                  <circle
                    cx="50"
                    cy="50"
                    r="45"
                    fill="none"
                    stroke="var(--border-primary)"
                    strokeWidth="8"
                  />
                  <circle
                    cx="50"
                    cy="50"
                    r="45"
                    fill="none"
                    stroke="url(#gradient)"
                    strokeWidth="8"
                    strokeLinecap="round"
                    strokeDasharray={`${(dedupStats?.savings_percentage || 0) * 2.827} 282.7`}
                    transform="rotate(-90 50 50)"
                  />
                  <defs>
                    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
                      <stop offset="0%" stopColor="#10b981" />
                      <stop offset="100%" stopColor="#059669" />
                    </linearGradient>
                  </defs>
                </svg>
                <div className="dedup-rate__value">
                  <span className="dedup-rate__number">{(dedupStats?.savings_percentage || 0).toFixed(1)}</span>
                  <span className="dedup-rate__symbol">%</span>
                </div>
              </div>
              <div className="dedup-rate__details">
                <div className="dedup-rate__detail">
                  <span className="dedup-rate__detail-value">{(stats?.deduplication_ratio || 1).toFixed(2)}x</span>
                  <span className="dedup-rate__detail-label">Compression Ratio</span>
                </div>
                <div className="dedup-rate__detail">
                  <span className="dedup-rate__detail-value">{formatNumber(stats?.deduplicated_uploads || 0)}</span>
                  <span className="dedup-rate__detail-label">Duplicate Uploads</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {dedupStats && dedupStats.most_referenced_artifacts.length > 0 && (
        <section className="dashboard__section">
          <h2 className="dashboard__section-title">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
            </svg>
            Top Referenced Artifacts
          </h2>
          <p className="dashboard__section-description">
            These artifacts are referenced most frequently across your storage, maximizing deduplication savings.
          </p>
          <DataTable
            data={dedupStats.most_referenced_artifacts.slice(0, 10)}
            columns={artifactColumns}
            keyExtractor={(item) => item.artifact_id}
            emptyMessage="No referenced artifacts found"
            className="artifacts-table"
          />
        </section>
      )}
    </div>
  );
}

export default Dashboard;
