import { useState, useEffect, useContext, useMemo } from 'react'
import { Plus, Search, LayoutGrid, List, ChevronUp, ChevronDown, Languages, Globe, FileEdit } from 'lucide-react'
import { AppContext } from '../App'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import { api } from '../utils/api'
import Modal from '../components/Modal'
import BulkSelectBar from '../components/BulkSelectBar'
import { useToast } from '../components/ToastContainer'
import { SkeletonCard, SkeletonTable } from '../components/SkeletonLoader'
import TranslationDetailPanel from '../components/TranslationDetailPanel'
import ApproverMultiSelect from '../components/ApproverMultiSelect'
import { AVAILABLE_LANGUAGES, TRANSLATION_STATUS_COLORS } from '../utils/translations'


const SORT_OPTIONS = [
  { value: 'updated_at', dir: 'desc', labelKey: 'translations.sortRecentlyUpdated' },
  { value: 'created_at', dir: 'desc', labelKey: 'translations.sortNewest' },
  { value: 'created_at', dir: 'asc', labelKey: 'translations.sortOldest' },
  { value: 'title', dir: 'asc', labelKey: 'translations.sortTitleAZ' },
]

export default function Translations() {
  const { t } = useLanguage()
  const { brands, teamMembers } = useContext(AppContext)
  const { user, canDeleteResource } = useAuth()
  const toast = useToast()

  const [translations, setTranslations] = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ brand: '', status: '', creator: '' })
  const [searchTerm, setSearchTerm] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [selectedTranslation, setSelectedTranslation] = useState(null)
  const [newTranslation, setNewTranslation] = useState({ title: '', source_language: 'EN', source_content: '', brand_id: '', post_id: '', approver_ids: [] })
  const [saving, setSaving] = useState(false)
  const [posts, setPosts] = useState([])
  const [showCreatePost, setShowCreatePost] = useState(false)
  const [newPostTitle, setNewPostTitle] = useState('')
  const [creatingPost, setCreatingPost] = useState(false)

  // Bulk select
  const [selectedIds, setSelectedIds] = useState(new Set())
  const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false)

  // View + sort
  const [viewMode, setViewMode] = useState('list')
  const [sortOption, setSortOption] = useState(0)
  const [listSortBy, setListSortBy] = useState('updated_at')
  const [listSortDir, setListSortDir] = useState('desc')

  const [assignableUsers, setAssignableUsers] = useState([])

  useEffect(() => {
    loadTranslations()
    api.get('/users/assignable').then(res => setAssignableUsers(Array.isArray(res) ? res : [])).catch(() => {})
    api.get('/posts').then(res => setPosts(Array.isArray(res) ? res : [])).catch(() => {})
  }, [])

  const loadTranslations = async () => {
    try {
      const res = await api.get('/translations')
      setTranslations(Array.isArray(res) ? res : [])
    } catch (err) {
      console.error('Failed to load translations:', err)
      toast.error(t('translations.loadFailed'))
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async () => {
    if (!newTranslation.title) {
      toast.error(t('translations.titleRequired'))
      return
    }
    if (!newTranslation.source_content) {
      toast.error(t('translations.sourceContentRequired'))
      return
    }
    setSaving(true)
    try {
      const created = await api.post('/translations', {
        ...newTranslation,
        approver_ids: newTranslation.approver_ids.length > 0 ? newTranslation.approver_ids.join(',') : null,
        post_id: newTranslation.post_id || null,
      })
      toast.success(t('translations.created'))
      setShowCreateModal(false)
      setNewTranslation({ title: '', source_language: 'EN', source_content: '', brand_id: '', post_id: '', approver_ids: [] })
      loadTranslations()
      setSelectedTranslation(created)
    } catch (err) {
      console.error('Create failed:', err)
      toast.error(t('translations.createFailed'))
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id) => {
    try {
      await api.delete(`/translations/${id}`)
      toast.success(t('translations.deleted'))
      setSelectedTranslation(null)
      loadTranslations()
    } catch (err) {
      toast.error(t('translations.deleteFailed'))
    }
  }

  const handleCreatePost = async () => {
    if (!newPostTitle.trim()) return
    setCreatingPost(true)
    try {
      const created = await api.post('/posts', { title: newPostTitle, status: 'draft' })
      const postId = created.Id || created.id || created._id
      setPosts(prev => [created, ...prev])
      setNewTranslation(f => ({ ...f, post_id: String(postId) }))
      setShowCreatePost(false)
      setNewPostTitle('')
      toast.success(t('translations.postCreated'))
    } catch (err) {
      toast.error(t('translations.postCreateFailed'))
    } finally {
      setCreatingPost(false)
    }
  }

  const handleBulkDelete = async () => {
    try {
      await api.post('/translations/bulk-delete', { ids: [...selectedIds] })
      toast.success(t('translations.deleted'))
      setSelectedIds(new Set())
      setShowBulkDeleteConfirm(false)
      loadTranslations()
    } catch (err) {
      toast.error(t('translations.deleteFailed'))
    }
  }

  const toggleSelect = (id) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    if (selectedIds.size === sortedTranslations.length) setSelectedIds(new Set())
    else setSelectedIds(new Set(sortedTranslations.map(t => t.Id)))
  }

  const filteredTranslations = useMemo(() => {
    return translations.filter(t => {
      if (filters.brand && String(t.brand_id) !== filters.brand) return false
      if (filters.status && t.status !== filters.status) return false
      if (filters.creator && String(t.created_by_user_id) !== filters.creator) return false
      if (searchTerm && !t.title?.toLowerCase().includes(searchTerm.toLowerCase())) return false
      return true
    })
  }, [translations, filters, searchTerm])

  const sortedTranslations = useMemo(() => {
    const sBy = viewMode === 'grid' ? SORT_OPTIONS[sortOption].value : listSortBy
    const sDir = viewMode === 'grid' ? SORT_OPTIONS[sortOption].dir : listSortDir
    return [...filteredTranslations].sort((a, b) => {
      let cmp = 0
      if (sBy === 'updated_at') {
        cmp = (a.UpdatedAt || a.updated_at || '').localeCompare(b.UpdatedAt || b.updated_at || '')
      } else if (sBy === 'created_at') {
        cmp = (a.CreatedAt || a.created_at || '').localeCompare(b.CreatedAt || b.created_at || '')
      } else if (sBy === 'title') {
        cmp = (a.title || '').localeCompare(b.title || '')
      } else if (sBy === 'status') {
        cmp = (a.status || '').localeCompare(b.status || '')
      }
      return sDir === 'asc' ? cmp : -cmp
    })
  }, [filteredTranslations, viewMode, sortOption, listSortBy, listSortDir])

  const toggleListSort = (col) => {
    if (listSortBy === col) setListSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setListSortBy(col); setListSortDir('asc') }
  }

  const SortIcon = ({ col }) => {
    if (listSortBy !== col) return null
    return listSortDir === 'asc'
      ? <ChevronUp className="w-3 h-3 inline ml-0.5" />
      : <ChevronDown className="w-3 h-3 inline ml-0.5" />
  }

  const formatDate = (dateStr) => {
    if (!dateStr) return '—'
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  }

  const getLangLabel = (code) => AVAILABLE_LANGUAGES.find(l => l.code === code)?.label || code

  return (
    <div className="space-y-4 animate-fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">{t('translations.title')}</h1>
          <p className="text-sm text-text-secondary mt-1">{t('translations.subtitle')}</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center bg-surface-tertiary rounded-lg p-0.5">
            {[
              { mode: 'grid', icon: LayoutGrid, label: t('translations.grid') },
              { mode: 'list', icon: List, label: t('translations.list') },
            ].map(({ mode, icon: Icon, label }) => (
              <button
                key={mode}
                onClick={() => setViewMode(mode)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
                  viewMode === mode
                    ? 'bg-white text-text-primary shadow-sm'
                    : 'text-text-tertiary hover:text-text-secondary'
                }`}
              >
                <Icon className="w-3.5 h-3.5" />
                {label}
              </button>
            ))}
          </div>

          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors shadow-sm"
          >
            <Plus className="w-4 h-4" />
            <span className="font-medium">{t('translations.newTranslation')}</span>
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
          <input
            type="text"
            placeholder={t('translations.searchTranslations')}
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-surface transition-colors"
          />
        </div>

        <select
          value={filters.brand}
          onChange={e => setFilters(f => ({ ...f, brand: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('translations.allBrands')}</option>
          {brands.map(b => <option key={b._id} value={b._id}>{b.name}</option>)}
        </select>

        <select
          value={filters.status}
          onChange={e => setFilters(f => ({ ...f, status: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('translations.allStatuses')}</option>
          <option value="draft">{t('translations.status.draft')}</option>
          <option value="pending_review">{t('translations.status.pendingReview')}</option>
          <option value="approved">{t('translations.status.approved')}</option>
          <option value="rejected">{t('translations.status.rejected')}</option>
          <option value="revision_requested">{t('translations.status.revisionRequested')}</option>
        </select>

        <select
          value={filters.creator}
          onChange={e => setFilters(f => ({ ...f, creator: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('translations.allCreators')}</option>
          {teamMembers.map(m => <option key={m._id} value={m._id}>{m.name}</option>)}
        </select>

        {viewMode === 'grid' && (
          <select
            value={sortOption}
            onChange={e => setSortOption(Number(e.target.value))}
            className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
          >
            {SORT_OPTIONS.map((opt, i) => <option key={i} value={i}>{t(opt.labelKey)}</option>)}
          </select>
        )}
      </div>

      {/* Bulk select bar */}
      {selectedIds.size > 0 && (
        <BulkSelectBar
          count={selectedIds.size}
          onClear={() => setSelectedIds(new Set())}
          onDelete={() => setShowBulkDeleteConfirm(true)}
        />
      )}

      {/* Content */}
      {loading ? (
        viewMode === 'grid' ? <SkeletonCard count={6} /> : <SkeletonTable rows={5} cols={7} />
      ) : viewMode === 'grid' ? (
        /* Grid View */
        sortedTranslations.length === 0 ? (
          <div className="text-center py-16">
            <Languages className="w-12 h-12 text-text-tertiary mx-auto mb-3" />
            <p className="text-text-secondary">{t('translations.noTranslations')}</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {sortedTranslations.map(tr => (
              <div
                key={tr.Id}
                onClick={() => setSelectedTranslation(tr)}
                className="bg-surface rounded-xl border border-border p-5 hover:shadow-md transition-all cursor-pointer group"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-text-primary line-clamp-1">{tr.title}</h3>
                    <div className="flex items-center gap-2 mt-1">
                      <span className={`text-xs px-2 py-0.5 rounded-full ${TRANSLATION_STATUS_COLORS[tr.status] || 'bg-surface-tertiary text-text-secondary'}`}>
                        {tr.status?.replace('_', ' ')}
                      </span>
                      <span className="text-xs px-2 py-0.5 rounded-full bg-blue-50 text-blue-600 font-medium">
                        {getLangLabel(tr.source_language)}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2 text-xs text-text-tertiary flex-wrap">
                  {tr.brand_name && <span>{tr.brand_name}</span>}
                  {tr.post_name && <span className="flex items-center gap-1"><FileEdit className="w-3 h-3" />{tr.post_name}</span>}
                  {tr.creator_name && <span>by {tr.creator_name}</span>}
                  <span>{tr.translation_count || 0} {t('translations.languagesCount')}</span>
                </div>
              </div>
            ))}
          </div>
        )
      ) : (
        /* List View */
        sortedTranslations.length === 0 ? (
          <div className="text-center py-16">
            <Languages className="w-12 h-12 text-text-tertiary mx-auto mb-3" />
            <p className="text-text-secondary">{t('translations.noTranslations')}</p>
          </div>
        ) : (
          <div className="bg-surface rounded-xl border border-border overflow-hidden">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border bg-surface-secondary">
                  <th className="px-4 py-3 text-left w-10">
                    <input type="checkbox" checked={selectedIds.size === sortedTranslations.length && sortedTranslations.length > 0} onChange={toggleSelectAll} className="rounded border-border" />
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer" onClick={() => toggleListSort('title')}>
                    {t('translations.titleLabel')} <SortIcon col="title" />
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">
                    {t('translations.sourceLanguage')}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer" onClick={() => toggleListSort('status')}>
                    {t('translations.status')} <SortIcon col="status" />
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('translations.brand')}</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('translations.creator')}</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('translations.languagesLabel')}</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer" onClick={() => toggleListSort('updated_at')}>
                    {t('translations.updated')} <SortIcon col="updated_at" />
                  </th>
                </tr>
              </thead>
              <tbody>
                {sortedTranslations.map(tr => (
                  <tr
                    key={tr.Id}
                    onClick={() => setSelectedTranslation(tr)}
                    className="border-b border-border last:border-0 hover:bg-surface-secondary cursor-pointer transition-colors"
                  >
                    <td className="px-4 py-3" onClick={e => e.stopPropagation()}>
                      <input type="checkbox" checked={selectedIds.has(tr.Id)} onChange={() => toggleSelect(tr.Id)} className="rounded border-border" />
                    </td>
                    <td className="px-4 py-3 text-sm font-medium text-text-primary">{tr.title}</td>
                    <td className="px-4 py-3">
                      <span className="text-xs px-2 py-0.5 rounded-full bg-blue-50 text-blue-600 font-medium">
                        {getLangLabel(tr.source_language)}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full ${TRANSLATION_STATUS_COLORS[tr.status] || 'bg-surface-tertiary text-text-secondary'}`}>
                        {tr.status?.replace('_', ' ')}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-text-secondary">{tr.brand_name || '—'}</td>
                    <td className="px-4 py-3 text-sm text-text-secondary">{tr.creator_name || '—'}</td>
                    <td className="px-4 py-3 text-sm text-text-secondary">{tr.translation_count || 0}</td>
                    <td className="px-4 py-3 text-sm text-text-tertiary">{formatDate(tr.UpdatedAt || tr.updated_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )
      )}

      {/* Detail Panel */}
      {selectedTranslation && (
        <TranslationDetailPanel
          translation={selectedTranslation}
          onClose={() => setSelectedTranslation(null)}
          onUpdate={loadTranslations}
          onDelete={handleDelete}
          assignableUsers={assignableUsers}
          posts={posts}
        />
      )}

      {/* Create Modal */}
      <Modal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} title={t('translations.createTranslation')} size="md">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.titleLabel')} *</label>
            <input
              type="text"
              value={newTranslation.title}
              onChange={e => setNewTranslation(f => ({ ...f, title: 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('translations.titlePlaceholder')}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.sourceLanguage')} *</label>
            <select
              value={newTranslation.source_language}
              onChange={e => setNewTranslation(f => ({ ...f, source_language: 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"
            >
              {AVAILABLE_LANGUAGES.map(l => <option key={l.code} value={l.code}>{l.label} ({l.code})</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.sourceContent')} *</label>
            <textarea
              value={newTranslation.source_content}
              onChange={e => setNewTranslation(f => ({ ...f, source_content: 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 min-h-[120px] resize-y"
              placeholder={t('translations.sourceContentPlaceholder')}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.brand')}</label>
            <select
              value={newTranslation.brand_id}
              onChange={e => setNewTranslation(f => ({ ...f, brand_id: 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"
            >
              <option value="">—</option>
              {brands.map(b => <option key={b._id} value={b._id}>{b.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.linkedPost')}</label>
            {showCreatePost ? (
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  value={newPostTitle}
                  onChange={e => setNewPostTitle(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && handleCreatePost()}
                  className="flex-1 px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
                  placeholder={t('translations.newPostTitle')}
                  autoFocus
                />
                <button
                  onClick={handleCreatePost}
                  disabled={creatingPost || !newPostTitle.trim()}
                  className="px-3 py-2 bg-brand-primary text-white text-sm rounded-lg hover:bg-brand-primary-light disabled:opacity-50"
                >
                  {creatingPost ? '...' : t('common.create')}
                </button>
                <button
                  onClick={() => setShowCreatePost(false)}
                  className="px-2 py-2 text-sm text-text-secondary hover:text-text-primary"
                >
                  {t('common.cancel')}
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <select
                  value={newTranslation.post_id}
                  onChange={e => setNewTranslation(f => ({ ...f, post_id: e.target.value }))}
                  className="flex-1 px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
                >
                  <option value="">—</option>
                  {posts.map(p => <option key={p.Id || p.id || p._id} value={p.Id || p.id || p._id}>{p.title}</option>)}
                </select>
                <button
                  onClick={() => setShowCreatePost(true)}
                  className="flex items-center gap-1 px-3 py-2 text-sm text-brand-primary hover:text-brand-primary/80 font-medium whitespace-nowrap"
                >
                  <Plus className="w-3.5 h-3.5" />
                  {t('translations.createPost')}
                </button>
              </div>
            )}
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('translations.approvers')}</label>
            <ApproverMultiSelect
              selected={newTranslation.approver_ids}
              onChange={ids => setNewTranslation(f => ({ ...f, approver_ids: ids }))}
              users={assignableUsers}
            />
          </div>
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border">
            <button onClick={() => setShowCreateModal(false)} className="px-4 py-2 text-sm font-medium text-text-secondary hover:bg-surface-tertiary rounded-lg">
              {t('common.cancel')}
            </button>
            <button
              onClick={handleCreate}
              disabled={saving || !newTranslation.title || !newTranslation.source_content}
              className="px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shadow-sm"
            >
              {saving ? t('translations.creating') : t('common.create')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Bulk delete confirm */}
      <Modal
        isOpen={showBulkDeleteConfirm}
        onClose={() => setShowBulkDeleteConfirm(false)}
        title={t('translations.deleteTranslation')}
        isConfirm
        danger
        onConfirm={handleBulkDelete}
        confirmText={t('common.delete')}
      >
        {t('translations.bulkDeleteDesc', { count: selectedIds.size })}
      </Modal>
    </div>
  )
}
