import React from 'react'
import { ArrowLeft, Loader2, Play, AlertCircle, Check, Award } from 'lucide-react'
import { Button } from './Button'
import { useDatasetDetail } from '../hooks/useDatasets'

interface DatasetDetailProps {
  datasetId: string
  onBack: () => void
}

const SPLIT_STYLES: Record<string, string> = {
  train: 'bg-warm-state-info/10 text-warm-state-info',
  val: 'bg-warm-state-warning/10 text-warm-state-warning',
  test: 'bg-warm-state-success/10 text-warm-state-success',
}

const STATUS_STYLES: Record<string, { bg: string; text: string; label: string }> = {
  building: { bg: 'bg-warm-state-info/10', text: 'text-warm-state-info', label: 'Building' },
  ready: { bg: 'bg-warm-state-success/10', text: 'text-warm-state-success', label: 'Ready' },
  trained: { bg: 'bg-purple-100', text: 'text-purple-700', label: 'Trained' },
  failed: { bg: 'bg-warm-state-error/10', text: 'text-warm-state-error', label: 'Failed' },
  archived: { bg: 'bg-warm-border', text: 'text-warm-text-muted', label: 'Archived' },
}

const TRAINING_STATUS_STYLES: Record<string, { bg: string; text: string; label: string }> = {
  pending: { bg: 'bg-warm-state-warning/10', text: 'text-warm-state-warning', label: 'Pending' },
  scheduled: { bg: 'bg-warm-state-warning/10', text: 'text-warm-state-warning', label: 'Scheduled' },
  running: { bg: 'bg-warm-state-info/10', text: 'text-warm-state-info', label: 'Training' },
  completed: { bg: 'bg-warm-state-success/10', text: 'text-warm-state-success', label: 'Completed' },
  failed: { bg: 'bg-warm-state-error/10', text: 'text-warm-state-error', label: 'Failed' },
  cancelled: { bg: 'bg-warm-border', text: 'text-warm-text-muted', label: 'Cancelled' },
}

export const DatasetDetail: React.FC<DatasetDetailProps> = ({ datasetId, onBack }) => {
  const { dataset, isLoading, error } = useDatasetDetail(datasetId)

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20 text-warm-text-muted">
        <Loader2 size={24} className="animate-spin mr-2" />Loading dataset...
      </div>
    )
  }

  if (error || !dataset) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <button onClick={onBack} className="flex items-center gap-1 text-sm text-warm-text-muted hover:text-warm-text-secondary mb-4">
          <ArrowLeft size={16} />Back
        </button>
        <p className="text-warm-state-error">Failed to load dataset.</p>
      </div>
    )
  }

  const statusConfig = STATUS_STYLES[dataset.status] || STATUS_STYLES.ready
  const trainingStatusConfig = dataset.training_status
    ? TRAINING_STATUS_STYLES[dataset.training_status]
    : null

  // Determine if training button should be shown and enabled
  const isTrainingInProgress = dataset.training_status === 'running' || dataset.training_status === 'pending'
  const canStartTraining = dataset.status === 'ready' && !isTrainingInProgress

  // Determine status icon
  const statusIcon = dataset.status === 'trained'
    ? <Award size={14} className="text-purple-700" />
    : dataset.status === 'ready'
    ? <Check size={14} className="text-warm-state-success" />
    : dataset.status === 'failed'
    ? <AlertCircle size={14} className="text-warm-state-error" />
    : dataset.status === 'building'
    ? <Loader2 size={14} className="animate-spin text-warm-state-info" />
    : null

  return (
    <div className="p-8 max-w-7xl mx-auto">
      {/* Header */}
      <button onClick={onBack} className="flex items-center gap-1 text-sm text-warm-text-muted hover:text-warm-text-secondary mb-4">
        <ArrowLeft size={16} />Back to Datasets
      </button>

      <div className="flex items-center justify-between mb-6">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <h2 className="text-2xl font-bold text-warm-text-primary flex items-center gap-2">
              {dataset.name} {statusIcon}
            </h2>
            {/* Status Badge */}
            <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${statusConfig.bg} ${statusConfig.text}`}>
              {statusConfig.label}
            </span>
            {/* Training Status Badge */}
            {trainingStatusConfig && (
              <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${trainingStatusConfig.bg} ${trainingStatusConfig.text}`}>
                {isTrainingInProgress && <Loader2 size={12} className="mr-1 animate-spin" />}
                {trainingStatusConfig.label}
              </span>
            )}
          </div>
          {dataset.description && (
            <p className="text-sm text-warm-text-muted mt-1">{dataset.description}</p>
          )}
        </div>
        {/* Training Button */}
        {(dataset.status === 'ready' || dataset.status === 'trained') && (
          <Button
            disabled={isTrainingInProgress}
            className={isTrainingInProgress ? 'opacity-50 cursor-not-allowed' : ''}
          >
            {isTrainingInProgress ? (
              <><Loader2 size={14} className="mr-1 animate-spin" />Training...</>
            ) : (
              <><Play size={14} className="mr-1" />Start Training</>
            )}
          </Button>
        )}
      </div>

      {dataset.error_message && (
        <div className="bg-warm-state-error/10 border border-warm-state-error/20 rounded-lg p-4 mb-6 text-sm text-warm-state-error">
          {dataset.error_message}
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4 mb-8">
        {[
          ['Documents', dataset.total_documents],
          ['Images', dataset.total_images],
          ['Annotations', dataset.total_annotations],
          ['Split', `${(dataset.train_ratio * 100).toFixed(0)}/${(dataset.val_ratio * 100).toFixed(0)}/${((1 - dataset.train_ratio - dataset.val_ratio) * 100).toFixed(0)}`],
        ].map(([label, value]) => (
          <div key={String(label)} className="bg-warm-card border border-warm-border rounded-lg p-4">
            <p className="text-xs text-warm-text-muted uppercase font-semibold mb-1">{label}</p>
            <p className="text-2xl font-bold text-warm-text-primary font-mono">{value}</p>
          </div>
        ))}
      </div>

      {/* Document list */}
      <h3 className="text-lg font-semibold text-warm-text-primary mb-4">Documents</h3>
      <div className="bg-warm-card border border-warm-border rounded-lg overflow-hidden shadow-sm">
        <table className="w-full text-left">
          <thead className="bg-white border-b border-warm-border">
            <tr>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase">Document ID</th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase">Split</th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase">Pages</th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase">Annotations</th>
            </tr>
          </thead>
          <tbody>
            {dataset.documents.map(doc => (
              <tr key={doc.document_id} className="border-b border-warm-border hover:bg-warm-hover transition-colors">
                <td className="py-3 px-4 text-sm font-mono text-warm-text-secondary">{doc.document_id.slice(0, 8)}...</td>
                <td className="py-3 px-4">
                  <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-medium ${SPLIT_STYLES[doc.split] ?? 'bg-warm-border text-warm-text-muted'}`}>
                    {doc.split}
                  </span>
                </td>
                <td className="py-3 px-4 text-sm text-warm-text-muted font-mono">{doc.page_count}</td>
                <td className="py-3 px-4 text-sm text-warm-text-muted font-mono">{doc.annotation_count}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p className="text-xs text-warm-text-muted mt-4">
        Created: {new Date(dataset.created_at).toLocaleString()} | Updated: {new Date(dataset.updated_at).toLocaleString()}
        {dataset.dataset_path && <> | Path: <code className="text-xs">{dataset.dataset_path}</code></>}
      </p>
    </div>
  )
}
