import React, { useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { Loader2, Power, CheckCircle } from 'lucide-react';
import { Button } from './Button';
import { useModels, useModelDetail } from '../hooks';
import type { ModelVersionItem } from '../api/types';

const formatDate = (dateString: string | null): string => {
  if (!dateString) return 'N/A';
  return new Date(dateString).toLocaleString();
};

export const Models: React.FC = () => {
  const [selectedModel, setSelectedModel] = useState<ModelVersionItem | null>(null);
  const { models, isLoading, activateModel, isActivating } = useModels();
  const { model: modelDetail } = useModelDetail(selectedModel?.version_id ?? null);

  // Build chart data from selected model's metrics
  const metricsData = modelDetail ? [
    { name: 'Precision', value: (modelDetail.metrics_precision ?? 0) * 100 },
    { name: 'Recall', value: (modelDetail.metrics_recall ?? 0) * 100 },
    { name: 'mAP', value: (modelDetail.metrics_mAP ?? 0) * 100 },
  ] : [
    { name: 'Precision', value: 0 },
    { name: 'Recall', value: 0 },
    { name: 'mAP', value: 0 },
  ];

  // Build comparison chart from all models (with placeholder if empty)
  const chartData = models.length > 0
    ? models.slice(0, 4).map(m => ({
        name: m.version,
        value: (m.metrics_mAP ?? 0) * 100,
      }))
    : [
        { name: 'Model A', value: 0 },
        { name: 'Model B', value: 0 },
        { name: 'Model C', value: 0 },
        { name: 'Model D', value: 0 },
      ];

  return (
    <div className="p-8 max-w-7xl mx-auto flex gap-8">
      {/* Left: Job History */}
      <div className="flex-1">
        <h2 className="text-2xl font-bold text-warm-text-primary mb-6">Models & History</h2>
        <h3 className="text-lg font-semibold text-warm-text-primary mb-4">Model Versions</h3>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="animate-spin text-warm-text-muted" size={32} />
          </div>
        ) : models.length === 0 ? (
          <div className="text-center py-12 text-warm-text-muted">
            No model versions found. Complete a training task to create a model version.
          </div>
        ) : (
          <div className="space-y-4">
            {models.map(model => (
              <div
                key={model.version_id}
                onClick={() => setSelectedModel(model)}
                className={`bg-warm-card border rounded-lg p-5 shadow-sm cursor-pointer transition-colors ${
                  selectedModel?.version_id === model.version_id
                    ? 'border-warm-text-secondary'
                    : 'border-warm-border hover:border-warm-divider'
                }`}
              >
                <div className="flex justify-between items-start mb-2">
                   <div>
                     <h4 className="font-semibold text-warm-text-primary text-lg mb-1">
                       {model.name}
                       {model.is_active && <CheckCircle size={16} className="inline ml-2 text-warm-state-info" />}
                     </h4>
                     <p className="text-sm text-warm-text-muted">Trained {formatDate(model.trained_at)}</p>
                   </div>
                   <div className="flex gap-1.5 items-center">
                     {(model.model_type ?? 'base') === 'finetune' && (
                       <span className="px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700">
                         Fine-tuned
                       </span>
                     )}
                     {model.gating_status && model.gating_status !== 'skipped' && (
                       <span className={`px-2 py-0.5 rounded text-xs font-medium ${
                         model.gating_status === 'pass' ? 'bg-green-100 text-green-700'
                         : model.gating_status === 'review' ? 'bg-yellow-100 text-yellow-700'
                         : model.gating_status === 'reject' ? 'bg-red-100 text-red-700'
                         : 'bg-gray-100 text-gray-600'
                       }`}>
                         {model.gating_status === 'pass' ? 'PASS'
                         : model.gating_status === 'review' ? 'REVIEW'
                         : model.gating_status === 'reject' ? 'REJECT'
                         : model.gating_status.toUpperCase()}
                       </span>
                     )}
                     <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                       model.is_active
                         ? 'bg-warm-state-info/10 text-warm-state-info'
                         : 'bg-warm-selected text-warm-state-success'
                     }`}>
                       {model.is_active ? 'Active' : model.status}
                     </span>
                   </div>
                </div>

                <div className="mt-4 flex gap-8">
                   <div>
                     <span className="block text-xs text-warm-text-muted uppercase tracking-wide">Documents</span>
                     <span className="text-lg font-mono text-warm-text-secondary">{model.document_count}</span>
                   </div>
                   <div>
                     <span className="block text-xs text-warm-text-muted uppercase tracking-wide">mAP</span>
                     <span className="text-lg font-mono text-warm-text-secondary">
                       {model.metrics_mAP ? `${(model.metrics_mAP * 100).toFixed(1)}%` : 'N/A'}
                     </span>
                   </div>
                   <div>
                     <span className="block text-xs text-warm-text-muted uppercase tracking-wide">Version</span>
                     <span className="text-lg font-mono text-warm-text-secondary">{model.version}</span>
                   </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Right: Model Detail */}
      <div className="w-[400px]">
         <div className="bg-warm-card border border-warm-border rounded-lg p-6 shadow-card sticky top-8">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-xl font-bold text-warm-text-primary">Model Detail</h3>
              <span className={`text-sm font-medium ${
                selectedModel?.is_active ? 'text-warm-state-info' : 'text-warm-state-success'
              }`}>
                {selectedModel ? (selectedModel.is_active ? 'Active' : selectedModel.status) : '-'}
              </span>
            </div>

            <div className="mb-8">
              <p className="text-sm text-warm-text-muted mb-1">Model name</p>
              <p className="font-medium text-warm-text-primary">
                {selectedModel ? `${selectedModel.name} (${selectedModel.version})` : 'Select a model'}
              </p>
            </div>

            <div className="space-y-8">
               {/* Chart 1 */}
               <div>
                  <h4 className="text-sm font-semibold text-warm-text-secondary mb-4">Model Comparison (mAP)</h4>
                  <div className="h-40">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E6E4E1" />
                        <XAxis dataKey="name" tick={{fontSize: 10, fill: '#6B6B6B'}} axisLine={false} tickLine={false} />
                        <YAxis hide domain={[0, 100]} />
                        <Tooltip
                          cursor={{fill: '#F1F0ED'}}
                          contentStyle={{borderRadius: '8px', border: '1px solid #E6E4E1', boxShadow: '0 2px 5px rgba(0,0,0,0.05)'}}
                          formatter={(value: number) => [`${value.toFixed(1)}%`, 'mAP']}
                        />
                        <Bar dataKey="value" fill="#3A3A3A" radius={[4, 4, 0, 0]} barSize={32} />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
               </div>

               {/* Chart 2 */}
               <div>
                  <h4 className="text-sm font-semibold text-warm-text-secondary mb-4">Performance Metrics</h4>
                  <div className="h-40">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart data={metricsData}>
                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E6E4E1" />
                        <XAxis dataKey="name" tick={{fontSize: 10, fill: '#6B6B6B'}} axisLine={false} tickLine={false} />
                        <YAxis hide domain={[0, 100]} />
                        <Tooltip
                          cursor={{fill: '#F1F0ED'}}
                          formatter={(value: number) => [`${value.toFixed(1)}%`, 'Score']}
                        />
                        <Bar dataKey="value" fill="#3A3A3A" radius={[4, 4, 0, 0]} barSize={32} />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
               </div>
            </div>

            <div className="mt-8 space-y-3">
              {selectedModel && !selectedModel.is_active ? (
                <Button
                  className="w-full"
                  onClick={() => activateModel(selectedModel.version_id)}
                  disabled={isActivating}
                >
                  {isActivating ? (
                    <>
                      <Loader2 size={16} className="mr-2 animate-spin" />
                      Activating...
                    </>
                  ) : (
                    <>
                      <Power size={16} className="mr-2" />
                      Activate for Inference
                    </>
                  )}
                </Button>
              ) : (
                <Button className="w-full" disabled={!selectedModel}>
                  {selectedModel?.is_active ? (
                    <>
                      <CheckCircle size={16} className="mr-2" />
                      Currently Active
                    </>
                  ) : (
                    'Select a Model'
                  )}
                </Button>
              )}
              <div className="flex gap-3">
                 <Button variant="secondary" className="flex-1" disabled={!selectedModel}>View Logs</Button>
                 <Button variant="secondary" className="flex-1" disabled={!selectedModel}>Use as Base</Button>
              </div>
            </div>
         </div>
      </div>
    </div>
  );
};
