import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Experiment, ExperimentCreateInput, ExperimentType, ExperimentStatus, ExperimentMetric, CombinedKPIs } from '../types';
import { getExperiment, updateExperiment, deleteExperiment, calculateExperimentPerformance } from '../services/experiments';
import { ExperimentStatusBadge, ExperimentTypeBadge } from './ExperimentBadge';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer, ReferenceLine } from 'recharts';

interface ExperimentDetailProps {
  experimentId: string | null;
  onClose: () => void;
  salesData?: any[];
}

const ExperimentDetail: React.FC<ExperimentDetailProps> = ({ experimentId, onClose, salesData = [] }) => {
  const [experiment, setExperiment] = useState<Experiment | null>(null);
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState<Partial<Experiment>>({});

  const loadExperiment = useCallback(async () => {
    if (!experimentId) return;
    setLoading(true);
    try {
      const data = await getExperiment(experimentId);
      setExperiment(data);
      setFormData(data || {});
    } catch (e: any) {
      console.error('Failed to load experiment:', e);
    } finally {
      setLoading(false);
    }
  }, [experimentId]);

  useEffect(() => {
    if (experimentId) {
      loadExperiment();
    }
  }, [experimentId, loadExperiment]);

  const handleSave = async () => {
    if (!experimentId) return;
    setLoading(true);
    try {
      const updated = await updateExperiment(experimentId, formData);
      setExperiment(updated);
      setEditing(false);
    } catch (e: any) {
      alert(`Error saving: ${e.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleCalculateResults = async () => {
    if (!experiment || !salesData.length) return;
    setLoading(true);
    try {
      const perf = await calculateExperimentPerformance(experiment, salesData);
      const updated = await updateExperiment(experiment.id, perf);
      setExperiment(updated);
    } catch (e: any) {
      alert(`Error calculating results: ${e.message}`);
    } finally {
      setLoading(false);
    }
  };

  const chartData = useMemo(() => {
    if (!experiment || !salesData.length) return [];

    const asinSet = new Set(experiment.asins.map(a => a.toUpperCase()));
    const weeklyMap = new Map<string, any>();

    salesData.forEach(r => {
      const asin = (r.asin || '').toUpperCase();
      if (!asinSet.has(asin)) return;

      const weekNum = r.week || 1;
      const yearStr = r.year || new Date().getFullYear();
      const weekStr = `${yearStr}-W${String(weekNum).padStart(2, '0')}`;

      if (!weeklyMap.has(weekStr)) {
        const d = new Date(yearStr, 0, 1 + (weekNum - 1) * 7);
        weeklyMap.set(weekStr, {
          name: weekStr,
          timestamp: d.getTime(),
          units: 0,
          revenue: 0,
          gv: 0,
          spend: 0,
        });
      }

      const w = weeklyMap.get(weekStr);
      w.units += r.unitsTotal || 0;
      w.revenue += r.salesTotal || 0;
      w.gv += r.glanceViews || 0;
      w.spend += r.cost || 0;
    });

    const arr = Array.from(weeklyMap.values()).map(w => ({
      ...w,
      cvr: w.gv > 0 ? (w.units / w.gv) * 100 : 0,
      acos: w.revenue > 0 ? (w.spend / w.revenue) * 100 : 0
    })).sort((a, b) => a.timestamp - b.timestamp);

    return arr.slice(-16); // Let's keep the last 16 weeks to ensure enough window before and during
  }, [experiment, salesData]);

  const getChartMetricColor = (metric: string) => {
    switch (metric) {
      case 'cvr': return '#34d399'; // emerald
      case 'gv': return '#a78bfa'; // purple 
      case 'acos': return '#fb7185'; // rose
      case 'revenue': return '#fbbf24'; // amber
      default: return '#818cf8'; // indigo for units
    }
  };

  const formatChartMetric = (val: number, metric: string) => {
    if (metric === 'cvr' || metric === 'acos' || metric === 'ctr') return `${val.toFixed(1)}%`;
    if (metric === 'revenue' || metric === 'cost') return `€${Math.round(val).toLocaleString('de-DE')}`;
    return Math.round(val).toLocaleString('de-DE');
  };

  if (!experimentId) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-700">
          <div className="flex items-center gap-3">
            {editing ? (
              <input
                type="text"
                value={formData.name || ''}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="text-xl font-bold bg-slate-800 border border-slate-600 rounded-lg px-3 py-1 text-white"
              />
            ) : (
              <h2 className="text-xl font-bold text-white">{experiment?.name || 'Loading...'}</h2>
            )}
            {experiment && (
              <div className="flex items-center gap-2">
                <ExperimentStatusBadge status={experiment.status} />
                <ExperimentTypeBadge type={experiment.type} />
              </div>
            )}
          </div>
          <div className="flex items-center gap-2">
            {editing ? (
              <>
                <button
                  onClick={() => { setEditing(false); setFormData(experiment || {}); }}
                  className="px-3 py-1.5 text-sm text-slate-400 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSave}
                  disabled={loading}
                  className="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-medium transition-colors"
                >
                  Save
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={() => setEditing(true)}
                  className="px-3 py-1.5 text-sm text-slate-400 hover:text-white transition-colors"
                >
                  Edit
                </button>
                <button
                  onClick={onClose}
                  className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
                >
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </>
            )}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading && !experiment ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500"></div>
            </div>
          ) : experiment ? (
            <div className="space-y-6">
              {/* Performance Cards */}
              {(experiment.experiment_units !== undefined) && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {experiment.type === 'pricing' && (
                    <>
                      <MetricDeltaCard title="Conversion Rate" baseline={experiment.baseline_cvr} experimentVal={experiment.experiment_cvr} format="percent" />
                      <MetricDeltaCard title="Total Revenue" baseline={experiment.baseline_revenue} experimentVal={experiment.experiment_revenue} format="currency" />
                    </>
                  )}
                  {experiment.type === 'advertising' && (
                    <>
                      <MetricDeltaCard title="Glance Views" baseline={experiment.baseline_gv} experimentVal={experiment.experiment_gv} format="number" />
                      <MetricDeltaCard title="ACOS" baseline={experiment.baseline_acos} experimentVal={experiment.experiment_acos} format="percent" invertColors={true} />
                    </>
                  )}
                  {experiment.type === 'content' && (
                    <>
                      <MetricDeltaCard title="Glance Views (SEO)" baseline={experiment.baseline_gv} experimentVal={experiment.experiment_gv} format="number" />
                      <MetricDeltaCard title="CVR (Persuasion)" baseline={experiment.baseline_cvr} experimentVal={experiment.experiment_cvr} format="percent" />
                    </>
                  )}
                  {experiment.type === 'promotion' && (
                    <>
                      <MetricDeltaCard title="Units Sold" baseline={experiment.baseline_units} experimentVal={experiment.experiment_units} format="number" />
                      <MetricDeltaCard title="Revenue" baseline={experiment.baseline_revenue} experimentVal={experiment.experiment_revenue} format="currency" />
                    </>
                  )}

                  <PerformanceCard
                    label="Primary Target Lift"
                    value={experiment.actual_lift_percent !== undefined
                      ? `${experiment.actual_lift_percent >= 0 ? '+' : ''}${experiment.actual_lift_percent}%`
                      : '—'}
                    color={experiment.actual_lift_percent !== undefined && experiment.actual_lift_percent >= 0 ? 'emerald' : 'red'}
                  />
                  <PerformanceCard
                    label="Significance"
                    value={experiment.statistical_significance
                      ? `${(experiment.statistical_significance * 100).toFixed(1)}%`
                      : 'Pending'}
                    color="purple"
                  />
                </div>
              )}

              {/* Calculate Results Button */}
              {experiment.status === 'completed' && experiment.experiment_units === undefined && salesData.length > 0 && (
                <button
                  onClick={handleCalculateResults}
                  className="w-full py-3 bg-indigo-600/20 border border-indigo-500/30 hover:bg-indigo-600/30 text-indigo-400 rounded-xl font-medium transition-colors"
                >
                  📊 Calculate Experiment Results
                </button>
              )}

              {/* Dynamic Metric Chart */}
              {chartData.length > 0 && (
                <div className="bg-slate-800/30 border border-slate-700 rounded-xl p-4">
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="text-sm font-semibold text-slate-300">
                      Timeline Impact ({experiment.primary_metric.toUpperCase()})
                    </h3>
                  </div>
                  <div className="h-48 w-full">
                    <ResponsiveContainer width="100%" height="100%">
                      <LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                        <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                        <XAxis
                          dataKey="name"
                          stroke="#94a3b8"
                          fontSize={10}
                          tickMargin={8}
                          tickFormatter={(val) => val.split('-')[1]} // Just show W12
                        />
                        <YAxis
                          stroke="#94a3b8"
                          fontSize={10}
                          tickFormatter={(val) => formatChartMetric(val, experiment.primary_metric)}
                          width={60}
                        />
                        <RechartsTooltip
                          contentStyle={{ backgroundColor: '#0f172a', borderColor: '#334155', borderRadius: '8px', fontSize: '12px' }}
                          labelStyle={{ color: '#94a3b8', marginBottom: '4px' }}
                          formatter={(value: number) => {
                            if (experiment.primary_metric === 'cvr') return [`${value.toFixed(1)}%`, 'CVR'];
                            if (experiment.primary_metric === 'acos') return [`${value.toFixed(1)}%`, 'ACOS'];
                            if (experiment.primary_metric === 'revenue') return [`€${value.toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`, 'Rev'];
                            return [value.toLocaleString('de-DE'), 'Units'];
                          }}
                        />
                        {/* Reference Line for Start Date */}
                        <ReferenceLine
                          x={(() => {
                            const dDate = new Date(experiment.start_date);
                            const jan1 = new Date(dDate.getFullYear(), 0, 1);
                            const dayOfYear = Math.floor((dDate.getTime() - jan1.getTime()) / 86400000) + 1;
                            const wN = Math.ceil((dayOfYear + jan1.getDay()) / 7);
                            return `${dDate.getFullYear()}-W${String(wN).padStart(2, '0')}`;
                          })()}
                          stroke="#e2e8f0"
                          strokeDasharray="3 3"
                          label={{ position: 'top', value: 'Started', fill: '#e2e8f0', fontSize: 10 }}
                        />
                        <Line
                          type="monotone"
                          dataKey={
                            experiment.primary_metric === 'revenue' ? 'revenue' :
                              experiment.primary_metric === 'acos' ? 'acos' :
                                experiment.primary_metric === 'cvr' ? 'cvr' :
                                  experiment.primary_metric === 'bsr' ? 'units' :
                                    experiment.primary_metric === 'ctr' ? 'gv' :
                                      'units' // Default fallback mapping
                          }
                          stroke={getChartMetricColor(experiment.primary_metric)}
                          origin="auto"
                          strokeWidth={3}
                          dot={{ fill: '#1e293b', r: 4, strokeWidth: 2 }}
                          activeDot={{ r: 6, fill: getChartMetricColor(experiment.primary_metric), strokeWidth: 0 }}
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  </div>
                </div>
              )}

              {/* Details Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Left Column */}
                <div className="space-y-4">
                  <DetailSection title="📋 Overview">
                    {editing ? (
                      <>
                        <textarea
                          value={formData.description || ''}
                          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                          className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
                          rows={3}
                          placeholder="Experiment description..."
                        />
                      </>
                    ) : (
                      <p className="text-slate-300 text-sm">{experiment.description || 'No description'}</p>
                    )}
                  </DetailSection>

                  <DetailSection title="🎯 Hypothesis">
                    {editing ? (
                      <textarea
                        value={formData.hypothesis || ''}
                        onChange={(e) => setFormData({ ...formData, hypothesis: e.target.value })}
                        className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
                        rows={3}
                        placeholder="What do you expect to happen?"
                      />
                    ) : (
                      <p className="text-slate-300 text-sm">{experiment.hypothesis || 'No hypothesis defined'}</p>
                    )}
                  </DetailSection>

                  <DetailSection title="📏 Metrics">
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-slate-400">Primary Metric:</span>
                        <span className="text-white font-medium capitalize">{experiment.primary_metric}</span>
                      </div>
                      {experiment.target_lift_percent && (
                        <div className="flex justify-between">
                          <span className="text-slate-400">Target Lift:</span>
                          <span className="text-white font-medium">{experiment.target_lift_percent}%</span>
                        </div>
                      )}
                    </div>
                  </DetailSection>
                </div>

                {/* Right Column */}
                <div className="space-y-4">
                  <DetailSection title="🎪 Experiment Details">
                    <div className="space-y-2 text-sm">
                      {editing ? (
                        <>
                          <div className="grid grid-cols-2 gap-2">
                            <select
                              value={formData.status || 'planned'}
                              onChange={(e) => setFormData({ ...formData, status: e.target.value as ExperimentStatus })}
                              className="bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                            >
                              <option value="planned">Planned</option>
                              <option value="active">Active</option>
                              <option value="completed">Completed</option>
                              <option value="paused">Paused</option>
                            </select>
                            <select
                              value={formData.type || 'pricing'}
                              onChange={(e) => setFormData({ ...formData, type: e.target.value as ExperimentType })}
                              className="bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                            >
                              <option value="pricing">Pricing</option>
                              <option value="advertising">Advertising</option>
                              <option value="content">Content</option>
                              <option value="promotion">Promotion</option>
                            </select>
                          </div>
                          <input
                            type="text"
                            value={formData.marketplace || ''}
                            onChange={(e) => setFormData({ ...formData, marketplace: e.target.value })}
                            className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                            placeholder="Marketplace (DE, UK, FR, IT, ES)"
                          />
                        </>
                      ) : (
                        <>
                          <div className="flex justify-between">
                            <span className="text-slate-400">Marketplace:</span>
                            <span className="text-white font-medium">{experiment.marketplace}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-400">Type:</span>
                            <span className="text-white font-medium capitalize">{experiment.type}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-400">Status:</span>
                            <span className="text-white font-medium capitalize">{experiment.status}</span>
                          </div>
                        </>
                      )}
                    </div>
                  </DetailSection>

                  <DetailSection title="📅 Timeline">
                    <div className="space-y-2 text-sm">
                      {editing ? (
                        <>
                          <div>
                            <label className="text-xs text-slate-400 block mb-1">Start Date</label>
                            <input
                              type="date"
                              value={formData.start_date || ''}
                              onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                              className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                            />
                          </div>
                          <div>
                            <label className="text-xs text-slate-400 block mb-1">End Date</label>
                            <input
                              type="date"
                              value={formData.end_date || ''}
                              onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
                              className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                            />
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="flex justify-between">
                            <span className="text-slate-400">Start Date:</span>
                            <span className="text-white">{new Date(experiment.start_date).toLocaleDateString()}</span>
                          </div>
                          {experiment.end_date && (
                            <div className="flex justify-between">
                              <span className="text-slate-400">End Date:</span>
                              <span className="text-white">{new Date(experiment.end_date).toLocaleDateString()}</span>
                            </div>
                          )}
                          {experiment.end_date && (
                            <div className="flex justify-between">
                              <span className="text-slate-400">Duration:</span>
                              <span className="text-white">
                                {Math.ceil((new Date(experiment.end_date).getTime() - new Date(experiment.start_date).getTime()) / (1000 * 60 * 60 * 24))} days
                              </span>
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  </DetailSection>

                  <DetailSection title="👤 Owner">
                    {editing ? (
                      <input
                        type="text"
                        value={formData.owner || ''}
                        onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
                        className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
                        placeholder="Owner name"
                      />
                    ) : (
                      <p className="text-slate-300 text-sm">{experiment.owner || 'Not assigned'}</p>
                    )}
                  </DetailSection>
                </div>
              </div>

              {/* ASINs */}
              <DetailSection title="📦 Target ASINs">
                <div className="flex flex-wrap gap-2">
                  {experiment.asins.map((asin, idx) => (
                    <span
                      key={idx}
                      className="px-2.5 py-1 bg-slate-800 border border-slate-600 rounded-lg text-sm text-slate-300 font-mono"
                    >
                      {asin}
                    </span>
                  ))}
                </div>
              </DetailSection>

              {/* Learnings */}
              <DetailSection title="💡 Learnings & Conclusions">
                {editing ? (
                  <textarea
                    value={formData.learnings || ''}
                    onChange={(e) => setFormData({ ...formData, learnings: e.target.value })}
                    className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
                    rows={4}
                    placeholder="What did you learn from this experiment?"
                  />
                ) : (
                  <p className="text-slate-300 text-sm whitespace-pre-wrap">
                    {experiment.learnings || 'No learnings recorded yet'}
                  </p>
                )}
              </DetailSection>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

// Performance Card Component
const PerformanceCard: React.FC<{ label: string; value: string; color: string }> = ({ label, value, color }) => {
  const colorClasses: Record<string, string> = {
    slate: 'bg-slate-500/10 border-slate-500/30 text-slate-400',
    indigo: 'bg-indigo-500/10 border-indigo-500/30 text-indigo-400',
    emerald: 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400',
    red: 'bg-red-500/10 border-red-500/30 text-red-400',
    purple: 'bg-purple-500/10 border-purple-500/30 text-purple-400',
  };

  return (
    <div className={`p-4 rounded-xl border ${colorClasses[color]}`}>
      <div className="text-xs opacity-70 mb-1">{label}</div>
      <div className="text-xl font-bold">{value}</div>
    </div>
  );
};

// Metric Delta Card Component
const MetricDeltaCard: React.FC<{
  title: string;
  baseline: number | undefined;
  experimentVal: number | undefined;
  format?: 'number' | 'currency' | 'percent';
  invertColors?: boolean;
}> = ({ title, baseline, experimentVal, format = 'number', invertColors = false }) => {
  if (baseline === undefined || experimentVal === undefined) return null;
  const delta = baseline > 0 ? ((experimentVal - baseline) / baseline) * 100 : 0;

  const isPositive = invertColors ? delta <= 0 : delta >= 0;
  const colorClass = isPositive ? 'text-emerald-400' : 'text-red-400';
  const bgClass = isPositive ? 'bg-emerald-500/10 border-emerald-500/30' : 'bg-red-500/10 border-red-500/30';

  const formatter = (val: number) => {
    if (format === 'percent') return `${val}%`;
    if (format === 'currency') return `€${val.toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
    return val.toLocaleString('de-DE');
  };

  return (
    <div className={`p-4 rounded-xl border ${bgClass}`}>
      <div className="text-xs font-semibold text-slate-300 mb-2">{title}</div>
      <div className="flex flex-col gap-1">
        <div className="flex items-end justify-between">
          <div className="text-2xl font-bold text-white">{formatter(experimentVal)}</div>
          <div className={`text-sm font-bold ${colorClass}`}>
            {delta > 0 ? '+' : ''}{delta.toFixed(1)}%
          </div>
        </div>
        <div className="text-[10px] text-slate-500 font-medium">vs {formatter(baseline)} baseline avg</div>
      </div>
    </div>
  );
};

// Detail Section Component
const DetailSection: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (
  <div className="bg-slate-800/30 border border-slate-700 rounded-xl p-4">
    <h3 className="text-sm font-semibold text-slate-300 mb-3">{title}</h3>
    {children}
  </div>
);

export default ExperimentDetail;
