import { useState, useEffect, useContext, useMemo } from 'react'
import { AlertCircle, Search, LayoutGrid, List, ChevronUp, ChevronDown, Link2 } from 'lucide-react'
import { AppContext } from '../App'
import { api, STATUS_CONFIG, PRIORITY_CONFIG } from '../utils/api'
import { useLanguage } from '../i18n/LanguageContext'
import { useToast } from '../components/ToastContainer'
import IssueDetailPanel from '../components/IssueDetailPanel'
import IssueCard from '../components/IssueCard'
import KanbanBoard from '../components/KanbanBoard'
import KanbanCard from '../components/KanbanCard'
import EmptyState from '../components/EmptyState'
import { SkeletonTable, SkeletonKanbanBoard } from '../components/SkeletonLoader'
import BulkSelectBar from '../components/BulkSelectBar'
import Modal from '../components/Modal'

const TYPE_OPTION_KEYS = [
  { value: 'request', labelKey: 'issues.typeRequest' },
  { value: 'correction', labelKey: 'issues.typeCorrection' },
  { value: 'complaint', labelKey: 'issues.typeComplaint' },
  { value: 'suggestion', labelKey: 'issues.typeSuggestion' },
  { value: 'other', labelKey: 'issues.typeOther' },
]

// Issue-specific status order for the kanban board
const ISSUE_STATUS_CONFIG = {
  new: STATUS_CONFIG.new,
  acknowledged: STATUS_CONFIG.acknowledged,
  in_progress: STATUS_CONFIG.in_progress,
  resolved: STATUS_CONFIG.resolved,
  declined: STATUS_CONFIG.declined,
}

export default function Issues() {
  const { t } = useLanguage()
  const toast = useToast()
  const { brands, teams } = useContext(AppContext)

  const [issues, setIssues] = useState([])
  const [counts, setCounts] = useState({})
  const [loading, setLoading] = useState(true)
  const [selectedIssue, setSelectedIssue] = useState(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [filters, setFilters] = useState({ status: '', category: '', type: '', priority: '', brand: '', team: '' })
  const [categories, setCategories] = useState([])
  const [teamMembers, setTeamMembers] = useState([])

  // View mode
  const [viewMode, setViewMode] = useState('board')

  // List sorting
  const [sortBy, setSortBy] = useState('created_at')
  const [sortDir, setSortDir] = useState('desc')

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

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

  const loadData = async () => {
    try {
      setLoading(true)
      const [issuesData, categoriesData, teamData] = await Promise.all([
        api.get('/issues'),
        api.get('/issues/categories'),
        api.get('/users/team'),
      ])
      setIssues(issuesData.issues || [])
      setCounts(issuesData.counts || {})
      setCategories(categoriesData || [])
      setTeamMembers(Array.isArray(teamData) ? teamData : [])
    } catch (err) {
      console.error('Failed to load issues:', err)
    } finally {
      setLoading(false)
    }
  }

  // Filtering
  const filteredIssues = useMemo(() => {
    let filtered = [...issues]
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      filtered = filtered.filter(i =>
        i.title?.toLowerCase().includes(term) ||
        i.submitter_name?.toLowerCase().includes(term) ||
        i.submitter_email?.toLowerCase().includes(term) ||
        i.category?.toLowerCase().includes(term)
      )
    }
    if (filters.status) filtered = filtered.filter(i => i.status === filters.status)
    if (filters.category) filtered = filtered.filter(i => i.category === filters.category)
    if (filters.type) filtered = filtered.filter(i => i.type === filters.type)
    if (filters.priority) filtered = filtered.filter(i => i.priority === filters.priority)
    if (filters.brand) filtered = filtered.filter(i => String(i.brand_id) === String(filters.brand))
    if (filters.team) filtered = filtered.filter(i => String(i.team_id) === String(filters.team))
    return filtered
  }, [issues, searchTerm, filters])

  // List sorting
  const sortedIssues = useMemo(() => {
    const priorityOrder = { urgent: 0, high: 1, medium: 2, low: 3 }
    const statusOrder = { new: 0, acknowledged: 1, in_progress: 2, resolved: 3, declined: 4 }
    return [...filteredIssues].sort((a, b) => {
      let cmp = 0
      if (sortBy === 'created_at') {
        cmp = (a.created_at || a.CreatedAt || '').localeCompare(b.created_at || b.CreatedAt || '')
      } else if (sortBy === 'title') {
        cmp = (a.title || '').localeCompare(b.title || '')
      } else if (sortBy === 'priority') {
        cmp = (priorityOrder[a.priority] ?? 2) - (priorityOrder[b.priority] ?? 2)
      } else if (sortBy === 'status') {
        cmp = (statusOrder[a.status] ?? 0) - (statusOrder[b.status] ?? 0)
      }
      return sortDir === 'asc' ? cmp : -cmp
    })
  }, [filteredIssues, sortBy, sortDir])

  const updateFilter = (key, value) => setFilters(f => ({ ...f, [key]: value }))
  const clearFilters = () => {
    setFilters({ status: '', category: '', type: '', priority: '', brand: '', team: '' })
    setSearchTerm('')
  }
  const hasActiveFilters = Object.values(filters).some(Boolean) || searchTerm

  const getAssigneeName = (assignedToId) => {
    if (!assignedToId) return '—'
    const member = teamMembers.find(m => m.id === assignedToId || m._id === assignedToId)
    return member?.name || '—'
  }

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

  // Drag and drop handlers
  const handleMoveIssue = async (issueId, newStatus) => {
    // Optimistic update — move the card instantly
    const prev = issues
    setIssues(issues.map(i => (i.Id || i.id) === issueId ? { ...i, status: newStatus } : i))
    setCounts(c => {
      const old = prev.find(i => (i.Id || i.id) === issueId)
      if (!old || old.status === newStatus) return c
      return { ...c, [old.status]: (c[old.status] || 1) - 1, [newStatus]: (c[newStatus] || 0) + 1 }
    })
    try {
      await api.patch(`/issues/${issueId}`, { status: newStatus })
      toast.success(t('issues.statusUpdated'))
    } catch (err) {
      console.error('Move issue failed:', err)
      toast.error(t('issues.failedToUpdateStatus'))
      // Rollback on error
      setIssues(prev)
    }
  }

  const handleBulkDelete = async () => {
    try {
      await api.post('/issues/bulk-delete', { ids: [...selectedIds] })
      toast.success(t('issues.issuesDeleted'))
      setSelectedIds(new Set())
      setShowBulkDeleteConfirm(false)
      loadData()
    } catch (err) {
      console.error('Bulk delete failed:', err)
      toast.error(t('common.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 === sortedIssues.length) setSelectedIds(new Set())
    else setSelectedIds(new Set(sortedIssues.map(i => i.Id || i.id)))
  }

  const copyPublicLink = () => {
    const base = `${window.location.origin}/submit-issue`
    const url = filters.team ? `${base}?team=${filters.team}` : base
    navigator.clipboard.writeText(url)
    toast.success(t('issues.linkCopied'))
  }

  const toggleSort = (col) => {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortBy(col); setSortDir('asc') }
  }

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

  if (loading) {
    return (
      <div className="space-y-4">
        {viewMode === 'board' ? <SkeletonKanbanBoard /> : <SkeletonTable rows={8} cols={5} />}
      </div>
    )
  }

  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 flex items-center gap-2">
            <AlertCircle className="w-7 h-7" />
            {t('issues.title')}
          </h1>
          <p className="text-text-secondary mt-1">{t('issues.subtitle')}</p>
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={copyPublicLink}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium border border-border rounded-lg hover:bg-surface-secondary transition-colors text-text-secondary"
            title={t('issues.copyPublicLink')}
          >
            <Link2 className="w-3.5 h-3.5" />
            {t('issues.copyPublicLink')}
          </button>

          {/* View switcher */}
          <div className="flex items-center bg-surface-tertiary rounded-lg p-0.5">
            {[
              { mode: 'board', icon: LayoutGrid, label: t('issues.board') },
              { mode: 'list', icon: List, label: t('issues.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>
        </div>
      </div>

      {/* Status Counts */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 stagger-children">
        {Object.entries(ISSUE_STATUS_CONFIG).map(([status, config]) => (
          <div
            key={status}
            className={`bg-surface rounded-lg border p-4 cursor-pointer hover:shadow-sm transition-all ${
              filters.status === status ? 'border-brand-primary ring-1 ring-brand-primary/20' : 'border-border'
            }`}
            onClick={() => updateFilter('status', filters.status === status ? '' : status)}
          >
            <div className="flex items-center gap-2 mb-1">
              <span className={`w-2 h-2 rounded-full ${config.dot}`}></span>
              <span className="text-xs font-medium text-text-tertiary uppercase">{config.label}</span>
            </div>
            <div className="text-2xl font-bold text-text-primary">{counts[status] || 0}</div>
          </div>
        ))}
      </div>

      {/* Search & Filters - always visible inline */}
      <div className="flex items-center gap-3 flex-wrap">
        {/* Search */}
        <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"
            placeholder={t('issues.searchPlaceholder')}
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
          />
        </div>

        <select
          value={filters.status}
          onChange={e => updateFilter('status', e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
        >
          <option value="">{t('issues.allStatuses')}</option>
          {Object.entries(ISSUE_STATUS_CONFIG).map(([key, config]) => (
            <option key={key} value={key}>{config.label}</option>
          ))}
        </select>

        <select
          value={filters.category}
          onChange={e => updateFilter('category', e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
        >
          <option value="">{t('issues.allCategories')}</option>
          {categories.map(cat => <option key={cat} value={cat}>{cat}</option>)}
        </select>

        <select
          value={filters.type}
          onChange={e => updateFilter('type', e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
        >
          <option value="">{t('issues.allTypes')}</option>
          {TYPE_OPTION_KEYS.map(opt => <option key={opt.value} value={opt.value}>{t(opt.labelKey)}</option>)}
        </select>

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

        <select
          value={filters.team || ''}
          onChange={e => updateFilter('team', e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
        >
          <option value="">{t('issues.allTeams')}</option>
          {(teams || []).map(tm => (
            <option key={tm.id || tm.Id} value={tm.id || tm.Id}>{tm.name}</option>
          ))}
        </select>

        <select
          value={filters.priority}
          onChange={e => updateFilter('priority', e.target.value)}
          className="px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 bg-surface"
        >
          <option value="">{t('issues.allPriorities')}</option>
          {Object.entries(PRIORITY_CONFIG).map(([key, config]) => (
            <option key={key} value={key}>{config.label}</option>
          ))}
        </select>

        {hasActiveFilters && (
          <button onClick={clearFilters} className="px-3 py-2 rounded-lg text-sm font-medium text-text-tertiary hover:text-text-primary">
            {t('issues.clearAll')}
          </button>
        )}
      </div>

      {/* Board View */}
      {viewMode === 'board' && (
        filteredIssues.length === 0 ? (
          <EmptyState
            icon={AlertCircle}
            title={t('issues.noIssuesFound')}
            description={hasActiveFilters ? t('issues.tryAdjustingFilters') : t('issues.noIssuesSubmitted')}
          />
        ) : (
          <KanbanBoard
            columns={Object.entries(ISSUE_STATUS_CONFIG).map(([id, cfg]) => ({ id, label: cfg.label, color: cfg.dot }))}
            items={filteredIssues}
            getItemId={(i) => i.Id || i.id}
            onMove={handleMoveIssue}
            emptyLabel={t('issues.noIssuesInColumn')}
            renderCard={(issue) => (
              <KanbanCard
                title={issue.title}
                thumbnail={issue.thumbnail_url}
                brandName={issue.brand_name}
                assigneeName={issue.submitter_name}
                date={issue.created_at || issue.CreatedAt}
                onClick={() => setSelectedIssue(issue)}
                tags={issue.category && (
                  <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-tertiary text-text-secondary font-medium">
                    {issue.category}
                  </span>
                )}
              />
            )}
          />
        )
      )}

      {/* List View */}
      {viewMode === 'list' && (
        sortedIssues.length === 0 ? (
          <EmptyState
            icon={AlertCircle}
            title={t('issues.noIssuesFound')}
            description={hasActiveFilters ? t('issues.tryAdjustingFilters') : t('issues.noIssuesSubmitted')}
          />
        ) : (
          <div className="bg-surface rounded-lg border border-border overflow-hidden">
            {selectedIds.size > 0 && (
              <BulkSelectBar
                selectedCount={selectedIds.size}
                onClearSelection={() => setSelectedIds(new Set())}
                onDelete={() => setShowBulkDeleteConfirm(true)}
              />
            )}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-surface-secondary border-b border-border">
                  <tr>
                    <th className="w-10 px-3 py-3" onClick={e => e.stopPropagation()}>
                      <input type="checkbox" checked={selectedIds.size === sortedIssues.length && sortedIssues.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 hover:text-text-primary" onClick={() => toggleSort('title')}>
                      {t('issues.tableTitle')} <SortIcon col="title" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('issues.tableSubmitter')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('issues.tableBrand')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('issues.tableCategory')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('issues.tableType')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleSort('priority')}>
                      {t('issues.tablePriority')} <SortIcon col="priority" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleSort('status')}>
                      {t('issues.tableStatus')} <SortIcon col="status" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('issues.tableAssignedTo')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleSort('created_at')}>
                      {t('issues.tableCreated')} <SortIcon col="created_at" />
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {sortedIssues.map(issue => {
                    const priorityConfig = PRIORITY_CONFIG[issue.priority] || PRIORITY_CONFIG.medium
                    const statusConfig = STATUS_CONFIG[issue.status] || STATUS_CONFIG.new
                    return (
                      <tr
                        key={issue.Id || issue.id}
                        onClick={() => setSelectedIssue(issue)}
                        className="hover:bg-surface-secondary cursor-pointer transition-colors"
                      >
                        <td className="w-10 px-3 py-3" onClick={e => e.stopPropagation()}>
                          <input type="checkbox" checked={selectedIds.has(issue.Id || issue.id)} onChange={() => toggleSelect(issue.Id || issue.id)} className="rounded border-border" />
                        </td>
                        <td className="px-4 py-3 text-sm font-medium text-text-primary">{issue.title}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">
                          <div>{issue.submitter_name}</div>
                          <div className="text-xs text-text-tertiary">{issue.submitter_email}</div>
                        </td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{issue.brand_name || issue.brandName || '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{issue.category || '—'}</td>
                        <td className="px-4 py-3 text-sm">
                          <span className="text-xs px-2 py-1 rounded-full bg-surface-tertiary text-text-secondary">
                            {(() => { const opt = TYPE_OPTION_KEYS.find(o => o.value === issue.type); return opt ? t(opt.labelKey) : issue.type })()}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm">
                          <span className={`text-xs px-2 py-1 rounded-full font-medium ${priorityConfig.bg} ${priorityConfig.text}`}>
                            {priorityConfig.label}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm">
                          <span className={`text-xs px-2 py-1 rounded-full font-medium flex items-center gap-1.5 w-fit ${statusConfig.bg} ${statusConfig.text}`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${statusConfig.dot}`}></span>
                            {statusConfig.label}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{getAssigneeName(issue.assigned_to_id)}</td>
                        <td className="px-4 py-3 text-sm text-text-tertiary">{formatDate(issue.created_at)}</td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )
      )}

      {/* Bulk Delete Confirm */}
      <Modal
        isOpen={showBulkDeleteConfirm}
        onClose={() => setShowBulkDeleteConfirm(false)}
        title={t('common.bulkDeleteConfirm').replace('{count}', selectedIds.size)}
        isConfirm
        danger
        confirmText={t('common.deleteSelected')}
        onConfirm={handleBulkDelete}
      >
        {t('common.bulkDeleteDesc')}
      </Modal>

      {/* Detail Panel */}
      {selectedIssue && (
        <IssueDetailPanel
          issue={selectedIssue}
          onClose={() => setSelectedIssue(null)}
          onUpdate={loadData}
          teamMembers={teamMembers}
          teams={teams}
        />
      )}
    </div>
  )
}
