import { useState, useEffect } from 'react'
import { Trash2, FileEdit, BarChart3 } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'
import { PLATFORMS } from '../utils/api'
import Modal from './Modal'
import TabbedModal from './TabbedModal'
import BudgetBar from './BudgetBar'

const TRACK_TYPES = {
  organic_social: { label: 'Organic Social' },
  paid_social: { label: 'Paid Social' },
  paid_search: { label: 'Paid Search (PPC)' },
  seo_content: { label: 'SEO / Content' },
  production: { label: 'Production' },
}

const TRACK_STATUSES = ['planned', 'active', 'paused', 'completed']

export default function TrackDetailPanel({ track, campaignId, onClose, onSave, onDelete, scrollToMetrics }) {
  const { t, currencySymbol } = useLanguage()
  const [form, setForm] = useState({})
  const [dirty, setDirty] = useState(false)
  const [saving, setSaving] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [activeTab, setActiveTab] = useState(scrollToMetrics ? 'metrics' : 'details')

  const trackId = track?._id || track?.id
  const isCreateMode = !trackId

  useEffect(() => {
    if (track) {
      setForm({
        name: track.name || '',
        type: track.type || 'organic_social',
        platform: track.platform || '',
        budget_allocated: track.budget_allocated || '',
        status: track.status || 'planned',
        notes: track.notes || '',
        budget_spent: track.budget_spent || '',
        revenue: track.revenue || '',
        impressions: track.impressions || '',
        clicks: track.clicks || '',
        conversions: track.conversions || '',
      })
      setDirty(isCreateMode)
    }
  }, [track])

  if (!track) return null

  const update = (field, value) => {
    setForm(f => ({ ...f, [field]: value }))
    setDirty(true)
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      const data = {
        name: form.name,
        type: form.type,
        platform: form.platform || null,
        budget_allocated: form.budget_allocated ? Number(form.budget_allocated) : 0,
        status: form.status,
        notes: form.notes,
        budget_spent: form.budget_spent ? Number(form.budget_spent) : 0,
        revenue: form.revenue ? Number(form.revenue) : 0,
        impressions: form.impressions ? Number(form.impressions) : 0,
        clicks: form.clicks ? Number(form.clicks) : 0,
        conversions: form.conversions ? Number(form.conversions) : 0,
      }
      await onSave(isCreateMode ? null : trackId, data)
      setDirty(false)
      if (isCreateMode) onClose()
    } finally {
      setSaving(false)
    }
  }

  const confirmDelete = async () => {
    setShowDeleteConfirm(false)
    await onDelete(trackId)
    onClose()
  }

  const typeInfo = TRACK_TYPES[form.type] || TRACK_TYPES.organic_social

  const tabs = isCreateMode
    ? [{ key: 'details', label: t('tracks.details'), icon: FileEdit }]
    : [
        { key: 'details', label: t('tracks.details'), icon: FileEdit },
        { key: 'metrics', label: t('tracks.metrics'), icon: BarChart3 },
      ]

  return (
    <>
      <TabbedModal
        onClose={onClose}
        size="md"
        header={
          <>
            <input
              type="text"
              value={form.name}
              onChange={e => update('name', e.target.value)}
              className="w-full text-lg font-semibold text-text-primary bg-transparent border-0 p-0 focus:outline-none focus:ring-0"
              placeholder={t('tracks.trackName')}
            />
            <div className="flex items-center gap-2 mt-2">
              <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-tertiary text-text-tertiary">
                {typeInfo.label}
              </span>
              <span className={`text-[11px] px-2 py-0.5 rounded-full font-medium ${
                form.status === 'active' ? 'bg-emerald-100 text-emerald-700' :
                form.status === 'paused' ? 'bg-amber-100 text-amber-700' :
                form.status === 'completed' ? 'bg-blue-100 text-blue-700' :
                'bg-gray-100 text-gray-600'
              }`}>
                {form.status?.charAt(0).toUpperCase() + form.status?.slice(1)}
              </span>
            </div>
          </>
        }
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        footer={
          <>
            <div className="flex items-center gap-2">
              {onDelete && !isCreateMode && (
                <button
                  onClick={() => setShowDeleteConfirm(true)}
                  className="p-2 text-text-tertiary hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                  title={t('common.delete')}
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              )}
            </div>
            <div className="flex items-center gap-2.5">
              {dirty && (
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className={`px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed shadow-sm ${saving ? 'btn-loading' : ''}`}
                >
                  {isCreateMode ? t('tracks.addTrack') : t('tasks.saveChanges')}
                </button>
              )}
            </div>
          </>
        }
      >
        {activeTab === 'details' && (
          <div className="p-6 space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.type')}</label>
                <select
                  value={form.type}
                  onChange={e => update('type', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                >
                  {Object.entries(TRACK_TYPES).map(([k, v]) => (
                    <option key={k} value={k}>{v.label}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.platform')}</label>
                <select
                  value={form.platform}
                  onChange={e => update('platform', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                >
                  <option value="">All / Multiple</option>
                  {Object.entries(PLATFORMS).map(([k, v]) => (
                    <option key={k} value={k}>{v.label}</option>
                  ))}
                  <option value="google_ads">Google Ads</option>
                </select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.budgetAllocated')} ({currencySymbol})</label>
                <input
                  type="number"
                  value={form.budget_allocated}
                  onChange={e => update('budget_allocated', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                  placeholder="0 for free/organic"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.status')}</label>
                <select
                  value={form.status}
                  onChange={e => update('status', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                >
                  {TRACK_STATUSES.map(s => (
                    <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>
                  ))}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.notes')}</label>
              <textarea
                value={form.notes}
                onChange={e => update('notes', e.target.value)}
                rows={2}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none resize-none"
                placeholder="Keywords, targeting details..."
              />
            </div>
          </div>
        )}

        {activeTab === 'metrics' && !isCreateMode && (
          <div className="p-6 space-y-3">
            {Number(form.budget_allocated) > 0 && (
              <div className="p-3 bg-surface-secondary rounded-lg">
                <BudgetBar budget={Number(form.budget_allocated)} spent={Number(form.budget_spent) || 0} height="h-2" />
                <div className="flex items-center gap-2 mt-2">
                  {Number(form.clicks) > 0 && Number(form.budget_spent) > 0 && (
                    <span className="text-[10px] text-text-tertiary">
                      CPC: {(Number(form.budget_spent) / Number(form.clicks)).toFixed(2)} {currencySymbol}
                    </span>
                  )}
                  {Number(form.impressions) > 0 && Number(form.clicks) > 0 && (
                    <span className="text-[10px] text-text-tertiary">
                      CTR: {(Number(form.clicks) / Number(form.impressions) * 100).toFixed(2)}%
                    </span>
                  )}
                </div>
              </div>
            )}

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.budgetSpent')} ({currencySymbol})</label>
                <input
                  type="number"
                  value={form.budget_spent}
                  onChange={e => update('budget_spent', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('tracks.revenue')} ({currencySymbol})</label>
                <input
                  type="number"
                  value={form.revenue}
                  onChange={e => update('revenue', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                />
              </div>
            </div>

            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('campaigns.impressions')}</label>
                <input
                  type="number"
                  value={form.impressions}
                  onChange={e => update('impressions', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('campaigns.clicks')}</label>
                <input
                  type="number"
                  value={form.clicks}
                  onChange={e => update('clicks', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('campaigns.conversions')}</label>
                <input
                  type="number"
                  value={form.conversions}
                  onChange={e => update('conversions', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                />
              </div>
            </div>
          </div>
        )}
      </TabbedModal>

      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        title={t('tracks.deleteTrack')}
        isConfirm
        danger
        confirmText={t('common.delete')}
        onConfirm={confirmDelete}
      >
        {t('tracks.deleteConfirm')}
      </Modal>
    </>
  )
}
