'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { HardDrive, Loader2, Image as ImageIcon, Film, Music, FileText, Archive, File } from 'lucide-react';
import api from '@/lib/api';

interface CategoryUsage {
  category: string;
  size: number;
  count: number;
}

interface StorageData {
  total_size: number;
  categories: CategoryUsage[];
}

export default function StorageDashboard() {
  const [data, setData] = useState<StorageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadStorageData();
  }, []);

  async function loadStorageData() {
    try {
      const res = await api.getStorageDashboard();
      setData(res);
    } catch (err: any) {
      setError(err.message || 'Failed to load storage data');
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--color-text-tertiary)' }} />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="flex-1 flex items-center justify-center text-red-500">
        {error || 'Failed to load'}
      </div>
    );
  }

  const categoryConfig: Record<string, { label: string; color: string; icon: any }> = {
    images: { label: 'Images', color: '#f59e0b', icon: ImageIcon },
    videos: { label: 'Videos', color: '#ef4444', icon: Film },
    audio: { label: 'Audio', color: '#22c55e', icon: Music },
    documents: { label: 'Documents', color: '#3b82f6', icon: FileText },
    archives: { label: 'Archives', color: '#8b5cf6', icon: Archive },
    other: { label: 'Other', color: '#9ca3af', icon: File },
  };

  const totalDriveSize = 100 * 1024 * 1024 * 1024; // Dummy 100GB capacity for visualization, could be dynamic

  return (
    <div className="flex-1 overflow-y-auto p-8 max-w-5xl mx-auto w-full">
      <div className="mb-8 flex items-center gap-4">
        <div className="p-3 rounded-xl" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
          <HardDrive className="w-6 h-6" style={{ color: 'var(--color-accent)' }} />
        </div>
        <div>
          <h1 className="text-3xl font-bold mb-1" style={{ color: 'var(--color-text-primary)' }}>Storage Overview</h1>
          <p style={{ color: 'var(--color-text-secondary)' }}>View and manage your drive usage</p>
        </div>
      </div>

      <div className="p-6 rounded-2xl mb-8" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
        <div className="flex justify-between items-end mb-4">
          <div>
            <span className="text-4xl font-bold" style={{ color: 'var(--color-text-primary)' }}>{formatSize(data.total_size)}</span>
            <span className="text-lg ml-2" style={{ color: 'var(--color-text-secondary)' }}>used</span>
          </div>
        </div>

        {/* Progress Bar */}
        <div className="h-4 w-full rounded-full overflow-hidden flex gap-0.5" style={{ backgroundColor: 'var(--color-bg-secondary)' }}>
          {data.categories.map(cat => {
            const pct = (cat.size / Math.max(data.total_size, 1)) * 100;
            if (pct === 0) return null;
            return (
              <motion.div
                key={cat.category}
                initial={{ width: 0 }}
                animate={{ width: `${pct}%` }}
                transition={{ duration: 1, ease: 'easeOut' }}
                className="h-full"
                style={{ backgroundColor: categoryConfig[cat.category]?.color || '#9ca3af' }}
                title={`${categoryConfig[cat.category]?.label || cat.category}: ${formatSize(cat.size)}`}
              />
            );
          })}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {data.categories.map((cat, idx) => {
          const config = categoryConfig[cat.category] || categoryConfig.other;
          const Icon = config.icon;
          return (
            <motion.div
              key={cat.category}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.1 }}
              className="p-5 rounded-xl flex items-center gap-4"
              style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}
            >
              <div className="p-3 rounded-lg flex-shrink-0" style={{ backgroundColor: `${config.color}20` }}>
                <Icon className="w-6 h-6" style={{ color: config.color }} />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium truncate" style={{ color: 'var(--color-text-primary)' }}>{config.label}</p>
                <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>{cat.count} items</p>
              </div>
              <div className="text-right">
                <p className="text-sm font-semibold" style={{ color: 'var(--color-text-primary)' }}>{formatSize(cat.size)}</p>
                <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                  {((cat.size / Math.max(data.total_size, 1)) * 100).toFixed(1)}%
                </p>
              </div>
            </motion.div>
          );
        })}
      </div>
    </div>
  );
}

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