import { useState, useEffect } from 'react'
import { traceDatabase, type TraceRecord } from '../utils/traceDatabase'

interface TraceSelectorProps {
  onTraceSelect: (traceId: string) => void
  onUploadNew: () => void
}

export default function TraceSelector({ onTraceSelect, onUploadNew }: TraceSelectorProps) {
  const [traces, setTraces] = useState<TraceRecord[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editingName, setEditingName] = useState('')

  useEffect(() => {
    loadTraces()
  }, [])

  const loadTraces = async () => {
    try {
      setLoading(true)
      const allTraces = await traceDatabase.getAllTraces()
      // Sort by upload date (newest first)
      allTraces.sort((a, b) => b.uploadedAt.getTime() - a.uploadedAt.getTime())
      setTraces(allTraces)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load traces')
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (confirm('Are you sure you want to delete this trace? This action cannot be undone.')) {
      try {
        await traceDatabase.deleteTrace(id)
        setTraces(traces.filter(t => t.id !== id))
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to delete trace')
      }
    }
  }

  const handleRename = async (id: string, newName: string) => {
    if (!newName.trim()) return

    try {
      await traceDatabase.updateTraceName(id, newName.trim())
      setTraces(traces.map(t => t.id === id ? { ...t, name: newName.trim() } : t))
      setEditingId(null)
      setEditingName('')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to rename trace')
    }
  }

  const startEdit = (trace: TraceRecord) => {
    setEditingId(trace.id)
    setEditingName(trace.name)
  }

  const cancelEdit = () => {
    setEditingId(null)
    setEditingName('')
  }

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  const formatDuration = (microseconds: number) => {
    const seconds = microseconds / 1000000
    if (seconds < 60) return `${seconds.toFixed(1)}s`
    const minutes = seconds / 60
    return `${minutes.toFixed(1)}m`
  }

  const formatDate = (date: Date) => {
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center',
        minHeight: '200px',
        fontFamily: 'system-ui, sans-serif'
      }}>
        <div>Loading traces...</div>
      </div>
    )
  }

  return (
    <div style={{ 
      padding: '20px',
      fontFamily: 'system-ui, sans-serif',
      maxWidth: '1000px',
      margin: '0 auto'
    }}>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '24px'
      }}>
        <h1 style={{ 
          fontSize: '24px', 
          color: '#495057', 
          margin: '0',
          fontWeight: '600'
        }}>
          Performance Traces ({traces.length})
        </h1>
        
        <button
          onClick={onUploadNew}
          style={{
            background: '#007bff',
            color: 'white',
            border: 'none',
            padding: '10px 20px',
            borderRadius: '6px',
            cursor: 'pointer',
            fontSize: '14px',
            fontWeight: '500'
          }}
        >
          + Upload New Trace
        </button>
      </div>

      {error && (
        <div style={{
          marginBottom: '20px',
          padding: '12px 16px',
          backgroundColor: '#f8d7da',
          color: '#721c24',
          border: '1px solid #f5c6cb',
          borderRadius: '6px',
          fontSize: '14px'
        }}>
          {error}
        </div>
      )}

      {traces.length === 0 ? (
        <div style={{
          textAlign: 'center',
          padding: '60px 20px',
          backgroundColor: '#f8f9fa',
          borderRadius: '8px',
          border: '1px solid #dee2e6'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '16px' }}>📊</div>
          <h3 style={{ 
            color: '#495057', 
            marginBottom: '8px',
            fontSize: '18px',
            fontWeight: '600'
          }}>
            No traces found
          </h3>
          <p style={{ 
            color: '#6c757d', 
            marginBottom: '20px',
            fontSize: '14px'
          }}>
            Upload your first Chrome DevTools Performance trace to get started.
          </p>
          <button
            onClick={onUploadNew}
            style={{
              background: '#007bff',
              color: 'white',
              border: 'none',
              padding: '12px 24px',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: '500'
            }}
          >
            Upload Trace File
          </button>
        </div>
      ) : (
        <div style={{
          display: 'grid',
          gap: '16px',
          gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))'
        }}>
          {traces.map((trace) => (
            <div
              key={trace.id}
              style={{
                background: 'white',
                border: '1px solid #dee2e6',
                borderRadius: '8px',
                padding: '20px',
                cursor: 'pointer',
                transition: 'all 0.2s ease',
                boxShadow: '0 2px 4px rgba(0,0,0,0.05)'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = '#007bff'
                e.currentTarget.style.boxShadow = '0 4px 8px rgba(0,123,255,0.15)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = '#dee2e6'
                e.currentTarget.style.boxShadow = '0 2px 4px rgba(0,0,0,0.05)'
              }}
              onClick={() => onTraceSelect(trace.id)}
            >
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'flex-start',
                marginBottom: '12px'
              }}>
                {editingId === trace.id ? (
                  <input
                    type="text"
                    value={editingName}
                    onChange={(e) => setEditingName(e.target.value)}
                    onBlur={() => handleRename(trace.id, editingName)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') handleRename(trace.id, editingName)
                      if (e.key === 'Escape') cancelEdit()
                      e.stopPropagation()
                    }}
                    onClick={(e) => e.stopPropagation()}
                    autoFocus
                    style={{
                      fontSize: '16px',
                      fontWeight: '600',
                      border: '1px solid #007bff',
                      borderRadius: '4px',
                      padding: '4px 8px',
                      background: 'white',
                      outline: 'none'
                    }}
                  />
                ) : (
                  <h3 
                    style={{ 
                      fontSize: '16px', 
                      fontWeight: '600',
                      color: '#495057',
                      margin: '0',
                      wordBreak: 'break-word'
                    }}
                  >
                    {trace.name}
                  </h3>
                )}

                <div style={{ display: 'flex', gap: '8px' }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      startEdit(trace)
                    }}
                    style={{
                      background: 'transparent',
                      border: 'none',
                      cursor: 'pointer',
                      fontSize: '14px',
                      color: '#6c757d',
                      padding: '4px'
                    }}
                    title="Rename"
                  >
                    ✏️
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      handleDelete(trace.id)
                    }}
                    style={{
                      background: 'transparent',
                      border: 'none',
                      cursor: 'pointer',
                      fontSize: '14px',
                      color: '#dc3545',
                      padding: '4px'
                    }}
                    title="Delete"
                  >
                    🗑️
                  </button>
                </div>
              </div>

              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                gap: '8px',
                fontSize: '13px',
                color: '#6c757d'
              }}>
                <div><strong>Events:</strong> {trace.eventCount.toLocaleString()}</div>
                <div><strong>Size:</strong> {formatFileSize(trace.fileSize)}</div>
                <div><strong>Duration:</strong> {formatDuration(trace.duration)}</div>
                <div><strong>Uploaded:</strong> {formatDate(trace.uploadedAt)}</div>
              </div>

              <div style={{
                marginTop: '12px',
                fontSize: '12px',
                color: '#868e96',
                textAlign: 'right'
              }}>
                Click to analyze →
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}