import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { AppLayout } from '../../components/layout/AppLayout';
import {
  getOptimizationMoves,
  createOptimizationMove,
  updateOptimizationMove,
  deleteOptimizationMove,
  acceptOptimizationMove,
  rejectOptimizationMove,
} from '../../api/optimizationMoves';
import type { OptimizationMove, OptimizationMoveCreate, MoveStatus, MoveType } from '../../types';
import {
  Plus, X, Search, Filter, TrendingUp, ArrowRight, CheckCircle, XCircle,
  Rocket, Zap, Target, Edit, Trash2, BarChart3,
} from 'lucide-react';

const statusColors: Record<MoveStatus, string> = {
  recommended: 'bg-blue-100 text-blue-700 border-blue-200',
  accepted: 'bg-emerald-100 text-emerald-700 border-emerald-200',
  rejected: 'bg-red-100 text-red-700 border-red-200',
  implemented: 'bg-purple-100 text-purple-700 border-purple-200',
};

const typeIcons: Record<MoveType, React.ElementType> = {
  budget_shift: ArrowRight,
  channel_change: BarChart3,
  target_audience: Target,
};

export function OptimizationMovesPage() {
  const { user } = useAuth();
  const companyId = user?.tenantId as string;

  const [moves, setMoves] = useState<OptimizationMove[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showCreate, setShowCreate] = useState(false);
  const [editingMove, setEditingMove] = useState<OptimizationMove | null>(null);
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState<'all' | MoveStatus>('all');
  const [filterType, setFilterType] = useState<'all' | MoveType>('all');

  const [form, setForm] = useState<OptimizationMoveCreate>({
    move_type: 'budget_shift',
    description: '',
    source_channel: '',
    target_channel: '',
    current_spend: null,
    recommended_spend: null,
    expected_impact: null,
    confidence: null,
  });

  const loadMoves = useCallback(async () => {
    if (!companyId) return;
    try {
      setLoading(true);
      const data = await getOptimizationMoves(companyId);
      setMoves(data);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load optimization moves');
    } finally {
      setLoading(false);
    }
  }, [companyId]);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!companyId) return;
    try {
      if (editingMove) {
        await updateOptimizationMove(companyId, editingMove.id, form);
      } else {
        await createOptimizationMove(companyId, form);
      }
      setShowCreate(false);
      setEditingMove(null);
      setForm({ move_type: 'budget_shift', description: '', source_channel: '', target_channel: '', current_spend: null, recommended_spend: null, expected_impact: null, confidence: null });
      await loadMoves();
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to save optimization move');
    }
  };

  const handleAccept = async (move: OptimizationMove) => {
    if (!companyId) return;
    try { await acceptOptimizationMove(companyId, move.id); await loadMoves(); }
    catch (e) { setError(e instanceof Error ? e.message : 'Failed to accept move'); }
  };

  const handleReject = async (move: OptimizationMove) => {
    if (!companyId) return;
    try { await rejectOptimizationMove(companyId, move.id); await loadMoves(); }
    catch (e) { setError(e instanceof Error ? e.message : 'Failed to reject move'); }
  };

  const handleDelete = async (move: OptimizationMove) => {
    if (!companyId) return;
    if (!confirm('Delete this optimization move?')) return;
    try { await deleteOptimizationMove(companyId, move.id); await loadMoves(); }
    catch (e) { setError(e instanceof Error ? e.message : 'Failed to delete move'); }
  };

  const startEdit = (move: OptimizationMove) => {
    setEditingMove(move);
    setForm({
      move_type: move.move_type,
      description: move.description,
      source_channel: move.source_channel,
      target_channel: move.target_channel,
      current_spend: move.current_spend,
      recommended_spend: move.recommended_spend,
      expected_impact: move.expected_impact,
      confidence: move.confidence,
    });
    setShowCreate(true);
  };

  const filtered = moves
    .filter(m => filterStatus === 'all' || m.status === filterStatus)
    .filter(m => filterType === 'all' || m.move_type === filterType)
    .filter(m => search === '' || m.description.toLowerCase().includes(search.toLowerCase()) || m.source_channel.toLowerCase().includes(search.toLowerCase()));

  const recommendedCount = moves.filter(m => m.status === 'recommended').length;
  const totalImpact = moves.filter(m => m.expected_impact && m.status !== 'rejected').reduce((sum, m) => sum + (m.expected_impact ?? 0), 0);

  return (
    <AppLayout title="Optimization Moves">
      <div data-testid="page-content">
      {/* Summary */}
      <div className="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
        <div className="rounded-xl border border-surface-200 bg-white p-5">
          <p className="text-sm font-medium text-surface-500">Recommended</p>
          <p className="mt-2 text-3xl font-bold text-blue-600">{recommendedCount}</p>
        </div>
        <div className="rounded-xl border border-surface-200 bg-white p-5">
          <p className="text-sm font-medium text-surface-500">Potential Impact</p>
          <p className="mt-2 text-3xl font-bold text-emerald-600">+${totalImpact.toLocaleString()}</p>
        </div>
        <div className="rounded-xl border border-surface-200 bg-white p-5">
          <p className="text-sm font-medium text-surface-500">Implemented</p>
          <p className="mt-2 text-3xl font-bold text-purple-600">{moves.filter(m => m.status === 'implemented').length}</p>
        </div>
      </div>

      {/* Toolbar */}
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-2">
          <div className="relative flex-1 sm:flex-initial">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-surface-400" />
            <input type="text" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search moves..."
              className="w-full rounded-lg border border-surface-300 py-2 pl-9 pr-4 text-sm outline-none focus:border-brand-500 sm:w-64" />
          </div>
          <select value={filterStatus} onChange={(e) => setFilterStatus(e.target.value as 'all' | MoveStatus)}
            className="rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 min-h-[44px]">
            <option value="all">All Status</option>
            <option value="recommended">Recommended</option>
            <option value="accepted">Accepted</option>
            <option value="rejected">Rejected</option>
            <option value="implemented">Implemented</option>
          </select>
          <select value={filterType} onChange={(e) => setFilterType(e.target.value as 'all' | MoveType)}
            className="rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 min-h-[44px]">
            <option value="all">All Types</option>
            <option value="budget_shift">Budget Shift</option>
            <option value="channel_change">Channel Change</option>
            <option value="target_audience">Target Audience</option>
          </select>
        </div>
        <button onClick={() => { setShowCreate(true); setEditingMove(null); setForm({ move_type: 'budget_shift', description: '', source_channel: '', target_channel: '', current_spend: null, recommended_spend: null, expected_impact: null, confidence: null }); }}
          className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 min-h-[44px]">
          <Plus className="h-4 w-4" /> Add Move
        </button>
      </div>

      {error && (
        <div className="mb-4 rounded-xl border border-red-200 bg-red-50 p-4">
          <p className="text-sm font-medium text-red-800">{error}</p>
          <button onClick={() => setError(null)} className="mt-1 text-sm text-red-600 underline">Dismiss</button>
        </div>
      )}

      {/* Modal */}
      {showCreate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-surface-900">{editingMove ? 'Edit Move' : 'New Optimization Move'}</h2>
              <button onClick={() => setShowCreate(false)} className="rounded-lg p-1.5 text-surface-400 hover:bg-surface-100">
                <X className="h-5 w-5" />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-surface-700">Type</label>
                  <select value={form.move_type} onChange={(e) => setForm({ ...form, move_type: e.target.value as MoveType })}
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 min-h-[44px]">
                    <option value="budget_shift">Budget Shift</option>
                    <option value="channel_change">Channel Change</option>
                    <option value="target_audience">Target Audience</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700">Confidence (%)</label>
                  <input type="number" min="0" max="100" value={form.confidence ?? ''}
                    onChange={(e) => setForm({ ...form, confidence: e.target.value ? Number(e.target.value) : null })}
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-surface-700">Description</label>
                <textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={2}
                  className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 resize-none" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-surface-700">Source Channel</label>
                  <input type="text" value={form.source_channel} onChange={(e) => setForm({ ...form, source_channel: e.target.value })} placeholder="e.g. Google Ads"
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700">Target Channel</label>
                  <input type="text" value={form.target_channel} onChange={(e) => setForm({ ...form, target_channel: e.target.value })} placeholder="e.g. Facebook"
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-surface-700">Current Spend ($)</label>
                  <input type="number" value={form.current_spend ?? ''} onChange={(e) => setForm({ ...form, current_spend: e.target.value ? Number(e.target.value) : null })}
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700">Recommended ($)</label>
                  <input type="number" value={form.recommended_spend ?? ''} onChange={(e) => setForm({ ...form, recommended_spend: e.target.value ? Number(e.target.value) : null })}
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700">Expected Impact ($)</label>
                  <input type="number" value={form.expected_impact ?? ''} onChange={(e) => setForm({ ...form, expected_impact: e.target.value ? Number(e.target.value) : null })}
                    className="mt-1 w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500" />
                </div>
              </div>
              <div className="flex justify-end gap-2 pt-2">
                <button type="button" onClick={() => setShowCreate(false)}
                  className="rounded-lg border border-surface-300 px-4 py-2 text-sm font-medium text-surface-700 hover:bg-surface-50 min-h-[44px]">Cancel</button>
                <button type="submit" className="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 min-h-[44px]">
                  {editingMove ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Moves List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="h-6 w-6 animate-spin rounded-full border-2 border-brand-600 border-t-transparent" />
          <span className="ml-3 text-sm text-surface-500">Loading optimization moves…</span>
        </div>
      ) : filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-surface-200 bg-white py-16">
          <Zap className="h-12 w-12 text-surface-300" />
          <p className="mt-4 text-sm font-medium text-surface-700">
            {search || filterStatus !== 'all' ? 'No moves match your filters' : 'No optimization moves yet'}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((move) => {
            const TypeIcon = typeIcons[move.move_type] || Zap;
            return (
              <div key={move.id} className="rounded-xl border border-surface-200 bg-white p-5">
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-3">
                    <div className="mt-1 rounded-lg bg-brand-50 p-2 text-brand-600">
                      <TypeIcon className="h-4 w-4" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-semibold text-surface-900">{move.description || move.move_type}</h3>
                        <span className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium ${statusColors[move.status]}`}>
                          {move.status}
                        </span>
                      </div>
                      {move.source_channel && move.target_channel && (
                        <div className="mt-1 flex items-center gap-2 text-xs text-surface-500">
                          <span>{move.source_channel}</span>
                          <ArrowRight className="h-3 w-3" />
                          <span>{move.target_channel}</span>
                        </div>
                      )}
                      <div className="mt-2 flex items-center gap-4 text-xs text-surface-500">
                        {move.current_spend && <span>Current: ${move.current_spend.toLocaleString()}</span>}
                        {move.recommended_spend && <span>Recommended: ${move.recommended_spend.toLocaleString()}</span>}
                        {move.expected_impact && <span className="text-emerald-600">Impact: +${move.expected_impact.toLocaleString()}</span>}
                        {move.confidence && <span>Confidence: {move.confidence}%</span>}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-1">
                    {move.status === 'recommended' && (
                      <>
                        <button onClick={() => handleAccept(move)} className="rounded-lg p-1.5 text-surface-400 hover:bg-emerald-50 hover:text-emerald-600" title="Accept">
                          <CheckCircle className="h-4 w-4" />
                        </button>
                        <button onClick={() => handleReject(move)} className="rounded-lg p-1.5 text-surface-400 hover:bg-red-50 hover:text-red-600" title="Reject">
                          <XCircle className="h-4 w-4" />
                        </button>
                      </>
                    )}
                    <button onClick={() => startEdit(move)} className="rounded-lg p-1.5 text-surface-400 hover:bg-surface-100 hover:text-surface-600" title="Edit">
                      <Edit className="h-4 w-4" />
                    </button>
                    <button onClick={() => handleDelete(move)} className="rounded-lg p-1.5 text-surface-400 hover:bg-red-50 hover:text-red-600" title="Delete">
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
      </div>
    </AppLayout>
  );
}
