import { useState, useEffect, useContext } from 'react'
import { Plus, DollarSign, Edit2, Trash2, Search, CreditCard, User, Building2, TrendingUp, TrendingDown } from 'lucide-react'
import { format } from 'date-fns'
import { AppContext } from '../App'
import { api } from '../utils/api'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import Modal from '../components/Modal'
import StatusBadge from '../components/StatusBadge'
import { SkeletonTable } from '../components/SkeletonLoader'

const CATEGORIES = [
  { value: 'marketing', label: 'Marketing' },
  { value: 'production', label: 'Production' },
  { value: 'equipment', label: 'Equipment' },
  { value: 'travel', label: 'Travel' },
  { value: 'other', label: 'Other' },
]

const DESTINATIONS = [
  { value: 'company_card', labelKey: 'budgets.companyCard', icon: CreditCard },
  { value: 'personal_account', labelKey: 'budgets.personalAccount', icon: User },
  { value: 'corporate_account', labelKey: 'budgets.corporateAccount', icon: Building2 },
  { value: 'other', labelKey: 'budgets.otherDest', icon: DollarSign },
]

const EMPTY_ENTRY = {
  label: '', amount: '', source: '', destination: '', campaign_id: '', project_id: '',
  category: 'marketing', date_received: new Date().toISOString().slice(0, 10), notes: '',
  type: 'income',
}

export default function Budgets() {
  const { t, currencySymbol } = useLanguage()
  const { brands } = useContext(AppContext)
  const { permissions } = useAuth()
  const canManageFinance = permissions?.canManageFinance
  const [entries, setEntries] = useState([])
  const [campaigns, setCampaigns] = useState([])
  const [projects, setProjects] = useState([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState(null)
  const [form, setForm] = useState(EMPTY_ENTRY)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [entryToDelete, setEntryToDelete] = useState(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [filterCategory, setFilterCategory] = useState('')
  const [filterDestination, setFilterDestination] = useState('')
  const [filterType, setFilterType] = useState('')

  useEffect(() => { loadAll() }, [])

  const loadAll = async () => {
    try {
      const [ent, camp, proj] = await Promise.all([
        api.get('/budget'),
        api.get('/campaigns'),
        api.get('/projects'),
      ])
      setEntries(ent.data || ent || [])
      setCampaigns(camp.data || camp || [])
      setProjects(proj.data || proj || [])
    } catch (err) {
      console.error('Failed to load budgets:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    try {
      const data = {
        label: form.label,
        amount: Number(form.amount),
        source: form.source || null,
        destination: form.destination || null,
        campaign_id: form.campaign_id ? Number(form.campaign_id) : null,
        project_id: form.project_id ? Number(form.project_id) : null,
        category: form.category,
        date_received: form.date_received,
        notes: form.notes,
        type: form.type || 'income',
      }
      if (editing) {
        await api.patch(`/budget/${editing._id || editing.id}`, data)
      } else {
        await api.post('/budget', data)
      }
      setShowModal(false)
      setEditing(null)
      setForm(EMPTY_ENTRY)
      loadAll()
    } catch (err) {
      console.error('Save failed:', err)
    }
  }

  const openEdit = (entry) => {
    setEditing(entry)
    setForm({
      label: entry.label || '',
      amount: entry.amount || '',
      source: entry.source || '',
      destination: entry.destination || '',
      campaign_id: entry.campaignId || entry.campaign_id || '',
      project_id: entry.project_id || '',
      category: entry.category || 'marketing',
      date_received: entry.dateReceived || entry.date_received || '',
      notes: entry.notes || '',
      type: entry.type || 'income',
    })
    setShowModal(true)
  }

  const handleDelete = async (id) => {
    setEntryToDelete(id)
    setShowDeleteConfirm(true)
  }

  const confirmDelete = async () => {
    if (!entryToDelete) return
    await api.delete(`/budget/${entryToDelete}`)
    setEntryToDelete(null)
    loadAll()
  }

  const filteredEntries = entries.filter(e => {
    if (searchQuery) {
      const q = searchQuery.toLowerCase()
      if (!(e.label || '').toLowerCase().includes(q) &&
          !(e.source || '').toLowerCase().includes(q) &&
          !(e.campaign_name || '').toLowerCase().includes(q) &&
          !(e.project_name || '').toLowerCase().includes(q) &&
          !(e.notes || '').toLowerCase().includes(q)) return false
    }
    if (filterCategory && e.category !== filterCategory) return false
    if (filterDestination && e.destination !== filterDestination) return false
    if (filterType && (e.type || 'income') !== filterType) return false
    return true
  })

  const totalIncome = filteredEntries.filter(e => (e.type || 'income') === 'income').reduce((sum, e) => sum + (e.amount || 0), 0)
  const totalExpenseAmt = filteredEntries.filter(e => e.type === 'expense').reduce((sum, e) => sum + (e.amount || 0), 0)
  const totalFiltered = totalIncome - totalExpenseAmt

  const destConfig = (val) => DESTINATIONS.find(d => d.value === val)

  if (loading) {
    return <SkeletonTable rows={6} cols={6} />
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">{t('budgets.title')}</h1>
          <p className="text-sm text-text-tertiary mt-0.5">{t('budgets.subtitle')}</p>
        </div>
        {canManageFinance && (
          <button
            onClick={() => { setEditing(null); setForm(EMPTY_ENTRY); setShowModal(true) }}
            className="flex items-center gap-1.5 px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light shadow-sm"
          >
            <Plus className="w-4 h-4" /> {t('budgets.addEntry')}
          </button>
        )}
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[200px] max-w-xs">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
          <input
            type="text"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder={t('budgets.searchEntries')}
            className="w-full pl-9 pr-3 py-2 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
          />
        </div>
        <select
          value={filterCategory}
          onChange={e => setFilterCategory(e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg bg-white focus:outline-none"
        >
          <option value="">{t('budgets.allCategories')}</option>
          {CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
        </select>
        <select
          value={filterDestination}
          onChange={e => setFilterDestination(e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg bg-white focus:outline-none"
        >
          <option value="">{t('budgets.allDestinations')}</option>
          {DESTINATIONS.map(d => <option key={d.value} value={d.value}>{t(d.labelKey)}</option>)}
        </select>

        {/* Type filter */}
        <div className="flex rounded-lg border border-border overflow-hidden">
          {[{ value: '', label: t('budgets.allTypes') }, { value: 'income', label: t('budgets.income') }, { value: 'expense', label: t('budgets.expense') }].map(opt => (
            <button
              key={opt.value}
              onClick={() => setFilterType(opt.value)}
              className={`px-3 py-1.5 text-xs font-medium transition-colors ${
                filterType === opt.value
                  ? opt.value === 'expense' ? 'bg-red-500 text-white' : opt.value === 'income' ? 'bg-emerald-500 text-white' : 'bg-brand-primary text-white'
                  : 'bg-white text-text-secondary hover:bg-surface-secondary'
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>

        {filteredEntries.length > 0 && (
          <div className="ml-auto flex items-center gap-3 text-sm text-text-tertiary">
            <span>{filteredEntries.length} {filteredEntries.length === 1 ? 'entry' : 'entries'}</span>
            <span className="text-emerald-600 font-semibold">+{totalIncome.toLocaleString()}</span>
            {totalExpenseAmt > 0 && <span className="text-red-500 font-semibold">-{totalExpenseAmt.toLocaleString()}</span>}
            <span className="font-bold text-text-primary">= {totalFiltered.toLocaleString()} {currencySymbol}</span>
          </div>
        )}
      </div>

      {/* Entries table */}
      <div className="section-card">
        {filteredEntries.length === 0 ? (
          <div className="py-16 text-center text-sm text-text-tertiary">
            {entries.length === 0 ? t('budgets.noEntries') : t('budgets.noMatch')}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-surface-secondary">
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">{t('budgets.label')}</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">{t('budgets.source')}</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">{t('budgets.destination')}</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">{t('budgets.linkedTo')}</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">{t('budgets.date')}</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">{t('budgets.amount')}</th>
                  {canManageFinance && <th className="px-4 py-3 w-20" />}
                </tr>
              </thead>
              <tbody className="divide-y divide-border-light">
                {filteredEntries.map(entry => {
                  const dest = destConfig(entry.destination)
                  const DestIcon = dest?.icon || DollarSign
                  return (
                    <tr key={entry.id || entry._id} className="hover:bg-surface-secondary">
                      <td className="px-4 py-3">
                        <div className="font-medium text-text-primary">{entry.label}</div>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-tertiary text-text-tertiary capitalize">{entry.category}</span>
                          <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${
                            (entry.type || 'income') === 'expense'
                              ? 'bg-red-50 text-red-600 border border-red-100'
                              : 'bg-emerald-50 text-emerald-600 border border-emerald-100'
                          }`}>
                            {(entry.type || 'income') === 'expense' ? t('budgets.expense') : t('budgets.income')}
                          </span>
                        </div>
                        {entry.notes && <p className="text-xs text-text-tertiary mt-0.5 truncate max-w-[200px]">{entry.notes}</p>}
                      </td>
                      <td className="px-4 py-3 text-text-secondary">{entry.source || <span className="text-text-tertiary">--</span>}</td>
                      <td className="px-4 py-3">
                        {entry.destination ? (
                          <span className="inline-flex items-center gap-1.5 text-xs">
                            <DestIcon className="w-3 h-3 text-text-tertiary" />
                            <span className="text-text-secondary">{t(dest?.labelKey || 'budgets.otherDest')}</span>
                          </span>
                        ) : <span className="text-text-tertiary">--</span>}
                      </td>
                      <td className="px-4 py-3">
                        {entry.campaign_name && (
                          <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-blue-50 text-blue-600 font-medium border border-blue-100">
                            {entry.campaign_name}
                          </span>
                        )}
                        {entry.project_name && (
                          <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-purple-50 text-purple-600 font-medium border border-purple-100">
                            {entry.project_name}
                          </span>
                        )}
                        {!entry.campaign_name && !entry.project_name && <span className="text-text-tertiary text-xs">{t('budgets.general')}</span>}
                      </td>
                      <td className="px-4 py-3 text-text-secondary whitespace-nowrap">
                        {entry.date_received ? format(new Date(entry.date_received), 'MMM d, yyyy') : '--'}
                      </td>
                      <td className={`px-4 py-3 text-right font-semibold whitespace-nowrap ${
                        (entry.type || 'income') === 'expense' ? 'text-red-500' : 'text-emerald-600'
                      }`}>
                        {(entry.type || 'income') === 'expense' ? '-' : '+'}{Number(entry.amount).toLocaleString()} {currencySymbol}
                      </td>
                      {canManageFinance && (
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-1">
                            <button onClick={() => openEdit(entry)} className="p-1.5 hover:bg-surface-tertiary rounded-lg text-text-tertiary hover:text-text-primary">
                              <Edit2 className="w-3.5 h-3.5" />
                            </button>
                            <button onClick={() => handleDelete(entry.id || entry._id)} className="p-1.5 hover:bg-red-50 rounded-lg text-text-tertiary hover:text-red-500">
                              <Trash2 className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </td>
                      )}
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => { setShowModal(false); setEditing(null) }}
        title={editing ? t('budgets.editEntry') : t('budgets.addEntry')}
      >
        <div className="space-y-4">
          {/* Income / Expense toggle */}
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">{t('budgets.type')}</label>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => setForm(f => ({ ...f, type: 'income' }))}
                className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium border-2 transition-all ${
                  form.type === 'income'
                    ? 'border-emerald-500 bg-emerald-50 text-emerald-700'
                    : 'border-border bg-white text-text-secondary hover:bg-surface-secondary'
                }`}
              >
                <TrendingUp className="w-4 h-4" />
                {t('budgets.income')}
              </button>
              <button
                type="button"
                onClick={() => setForm(f => ({ ...f, type: 'expense' }))}
                className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium border-2 transition-all ${
                  form.type === 'expense'
                    ? 'border-red-500 bg-red-50 text-red-700'
                    : 'border-border bg-white text-text-secondary hover:bg-surface-secondary'
                }`}
              >
                <TrendingDown className="w-4 h-4" />
                {t('budgets.expense')}
              </button>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.label')} *</label>
            <input
              type="text"
              value={form.label}
              onChange={e => setForm(f => ({ ...f, label: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder={t('budgets.labelPlaceholder')}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.amount')} ({currencySymbol}) *</label>
              <input
                type="number"
                value={form.amount}
                onChange={e => setForm(f => ({ ...f, amount: e.target.value }))}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                placeholder="50000"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1">{form.type === 'expense' ? t('budgets.dateExpensed') : t('budgets.dateReceived')} *</label>
              <input
                type="date"
                value={form.date_received}
                onChange={e => setForm(f => ({ ...f, date_received: e.target.value }))}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.source')}</label>
              <input
                type="text"
                value={form.source}
                onChange={e => setForm(f => ({ ...f, source: e.target.value }))}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
                placeholder={t('budgets.sourcePlaceholder')}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.destination')}</label>
              <select
                value={form.destination}
                onChange={e => setForm(f => ({ ...f, destination: e.target.value }))}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
              >
                <option value="">{t('budgets.selectDestination')}</option>
                {DESTINATIONS.map(d => <option key={d.value} value={d.value}>{t(d.labelKey)}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.category')}</label>
            <select
              value={form.category}
              onChange={e => setForm(f => ({ ...f, category: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none"
            >
              {CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.linkedTo')}</label>
            <div className="grid grid-cols-2 gap-3">
              <select
                value={form.campaign_id}
                onChange={e => setForm(f => ({ ...f, campaign_id: e.target.value, project_id: '' }))}
                disabled={!!form.project_id}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none disabled:opacity-50 disabled:bg-surface-secondary"
              >
                <option value="">{t('budgets.noCampaign')}</option>
                {campaigns.map(c => <option key={c._id || c.id} value={c._id || c.id}>{c.name}</option>)}
              </select>
              <select
                value={form.project_id}
                onChange={e => setForm(f => ({ ...f, project_id: e.target.value, campaign_id: '' }))}
                disabled={!!form.campaign_id}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none disabled:opacity-50 disabled:bg-surface-secondary"
              >
                <option value="">{t('budgets.noProject')}</option>
                {projects.map(p => <option key={p._id || p.id} value={p._id || p.id}>{p.name}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('budgets.notes')}</label>
            <textarea
              value={form.notes}
              onChange={e => setForm(f => ({ ...f, 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={t('budgets.notesPlaceholder')}
            />
          </div>

          <div className="flex justify-end gap-3 pt-4 border-t border-border">
            <button onClick={() => setShowModal(false)} className="px-4 py-2 text-sm text-text-secondary hover:bg-surface-tertiary rounded-lg">{t('common.cancel')}</button>
            <button
              onClick={handleSave}
              disabled={!form.label || !form.amount || !form.date_received}
              className="px-5 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"
            >
              {editing ? t('common.save') : t('budgets.addEntry')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Delete confirmation */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => { setShowDeleteConfirm(false); setEntryToDelete(null) }}
        title={t('budgets.deleteEntry')}
        isConfirm
        danger
        confirmText={t('common.delete')}
        onConfirm={confirmDelete}
      >
        {t('budgets.deleteConfirm')}
      </Modal>
    </div>
  )
}
