'use client'

/**
 * Arbeitsvorrat (Task Manager) - User Frontend
 *
 * Task management view with:
 * - All tasks extracted from emails
 * - Deadline tracking and reminders
 * - Priority-based organization
 *
 * See: docs/klausur-modul/UNIFIED-INBOX-SPECIFICATION.md
 */

import { useState, useEffect, useCallback } from 'react'

// API Base URL
const API_BASE = process.env.NEXT_PUBLIC_KLAUSUR_SERVICE_URL || 'http://localhost:8086'

// Types
interface Task {
  id: string
  title: string
  description: string
  status: 'pending' | 'in_progress' | 'completed'
  priority: 'urgent' | 'high' | 'medium' | 'low'
  deadline: string | null
  emailId: string | null
  sourceSubject: string | null
  sourceSender: string | null
  senderType: string | null
  aiExtracted: boolean
  confidenceScore: number | null
  createdAt: string
  updatedAt: string
}

interface DashboardStats {
  totalTasks: number
  pendingTasks: number
  inProgressTasks: number
  completedTasks: number
  overdueTasks: number
  dueToday: number
  dueThisWeek: number
  byPriority: Record<string, number>
  bySenderType: Record<string, number>
}

type FilterStatus = 'all' | 'pending' | 'in_progress' | 'completed'
type FilterPriority = 'all' | 'urgent' | 'high' | 'medium' | 'low'

export default function TasksPage() {
  const [tasks, setTasks] = useState<Task[]>([])
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [filterStatus, setFilterStatus] = useState<FilterStatus>('all')
  const [filterPriority, setFilterPriority] = useState<FilterPriority>('all')
  const [showCreateModal, setShowCreateModal] = useState(false)

  const fetchTasks = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      if (filterStatus !== 'all') {
        params.append('status', filterStatus)
      }
      if (filterPriority !== 'all') {
        params.append('priority', filterPriority)
      }
      params.append('include_completed', filterStatus === 'completed' ? 'true' : 'false')

      const [tasksRes, statsRes] = await Promise.all([
        fetch(`${API_BASE}/api/v1/mail/tasks?${params}`),
        fetch(`${API_BASE}/api/v1/mail/tasks/dashboard`),
      ])

      if (tasksRes.ok) {
        const data = await tasksRes.json()
        setTasks(data.tasks || [])
      }

      if (statsRes.ok) {
        const data = await statsRes.json()
        setStats(data)
      }
    } catch (err) {
      console.error('Failed to fetch tasks:', err)
    } finally {
      setLoading(false)
    }
  }, [filterStatus, filterPriority])

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

  const updateTaskStatus = async (taskId: string, status: string) => {
    try {
      await fetch(`${API_BASE}/api/v1/mail/tasks/${taskId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      })
      fetchTasks()
    } catch (err) {
      console.error('Failed to update task:', err)
    }
  }

  const priorityColors: Record<string, { bg: string; text: string; border: string }> = {
    urgent: { bg: 'bg-red-50', text: 'text-red-700', border: 'border-red-200' },
    high: { bg: 'bg-orange-50', text: 'text-orange-700', border: 'border-orange-200' },
    medium: { bg: 'bg-yellow-50', text: 'text-yellow-700', border: 'border-yellow-200' },
    low: { bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200' },
  }

  const priorityLabels: Record<string, string> = {
    urgent: 'Dringend',
    high: 'Hoch',
    medium: 'Mittel',
    low: 'Niedrig',
  }

  const statusLabels: Record<string, string> = {
    pending: 'Offen',
    in_progress: 'In Bearbeitung',
    completed: 'Erledigt',
  }

  const getOverdueIndicator = (deadline: string | null) => {
    if (!deadline) return null
    const deadlineDate = new Date(deadline)
    const now = new Date()
    const diffDays = Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))

    if (diffDays < 0) {
      return { label: 'Überfällig', color: 'bg-red-100 text-red-800', urgent: true }
    } else if (diffDays === 0) {
      return { label: 'Heute', color: 'bg-orange-100 text-orange-800', urgent: true }
    } else if (diffDays <= 3) {
      return { label: `In ${diffDays} Tag${diffDays > 1 ? 'en' : ''}`, color: 'bg-yellow-100 text-yellow-800', urgent: false }
    } else if (diffDays <= 7) {
      return { label: `In ${diffDays} Tagen`, color: 'bg-blue-100 text-blue-800', urgent: false }
    }
    return null
  }

  return (
    <div className="min-h-screen bg-slate-100">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-semibold text-slate-900">Arbeitsvorrat</h1>
            <p className="text-sm text-slate-500">Aufgaben aus E-Mails und manuelle Einträge</p>
          </div>
          <div className="flex items-center gap-4">
            <a
              href="/mail"
              className="px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50"
            >
              Zurück zur Inbox
            </a>
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 flex items-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              Aufgabe erstellen
            </button>
          </div>
        </div>
      </header>

      <div className="p-6">
        {/* Dashboard Stats */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4 mb-6">
            <StatCard label="Gesamt" value={stats.totalTasks} />
            <StatCard label="Offen" value={stats.pendingTasks} color="blue" />
            <StatCard label="In Bearbeitung" value={stats.inProgressTasks} color="yellow" />
            <StatCard label="Erledigt" value={stats.completedTasks} color="green" />
            <StatCard label="Überfällig" value={stats.overdueTasks} color="red" highlight={stats.overdueTasks > 0} />
            <StatCard label="Heute fällig" value={stats.dueToday} color="orange" highlight={stats.dueToday > 0} />
            <StatCard label="Diese Woche" value={stats.dueThisWeek} />
          </div>
        )}

        {/* Filters */}
        <div className="bg-white rounded-lg shadow p-4 mb-6">
          <div className="flex flex-wrap gap-4 items-center">
            {/* Status Filter */}
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-slate-700">Status:</span>
              <div className="flex gap-1">
                {(['all', 'pending', 'in_progress', 'completed'] as FilterStatus[]).map((status) => (
                  <button
                    key={status}
                    onClick={() => setFilterStatus(status)}
                    className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
                      filterStatus === status
                        ? 'bg-primary-600 text-white'
                        : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                    }`}
                  >
                    {status === 'all' ? 'Alle' : statusLabels[status]}
                  </button>
                ))}
              </div>
            </div>

            {/* Priority Filter */}
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-slate-700">Priorität:</span>
              <div className="flex gap-1">
                {(['all', 'urgent', 'high', 'medium', 'low'] as FilterPriority[]).map((priority) => (
                  <button
                    key={priority}
                    onClick={() => setFilterPriority(priority)}
                    className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
                      filterPriority === priority
                        ? 'bg-primary-600 text-white'
                        : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                    }`}
                  >
                    {priority === 'all' ? 'Alle' : priorityLabels[priority]}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Task List */}
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
          </div>
        ) : tasks.length === 0 ? (
          <div className="bg-white rounded-lg shadow p-12 text-center">
            <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
            <h3 className="text-lg font-medium text-slate-900 mb-2">Keine Aufgaben</h3>
            <p className="text-slate-500">
              {filterStatus !== 'all' || filterPriority !== 'all'
                ? 'Keine Aufgaben mit den gewählten Filtern gefunden.'
                : 'Lassen Sie E-Mails analysieren oder erstellen Sie Aufgaben manuell.'}
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {tasks.map((task) => {
              const colors = priorityColors[task.priority]
              const overdueInfo = getOverdueIndicator(task.deadline)

              return (
                <div
                  key={task.id}
                  className={`bg-white rounded-lg shadow border-l-4 ${colors.border} p-6 hover:shadow-md transition-shadow`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      {/* Header */}
                      <div className="flex items-center gap-3 mb-2">
                        <span className={`px-2 py-1 text-xs font-medium rounded ${colors.bg} ${colors.text}`}>
                          {priorityLabels[task.priority]}
                        </span>
                        {overdueInfo && (
                          <span className={`px-2 py-1 text-xs font-medium rounded ${overdueInfo.color}`}>
                            {overdueInfo.label}
                          </span>
                        )}
                        {task.aiExtracted && (
                          <span className="px-2 py-1 text-xs font-medium rounded bg-purple-100 text-purple-700 flex items-center gap-1">
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                            </svg>
                            KI
                          </span>
                        )}
                      </div>

                      {/* Title */}
                      <h3 className="text-lg font-semibold text-slate-900 mb-2">{task.title}</h3>

                      {/* Description */}
                      {task.description && (
                        <p className="text-slate-600 text-sm mb-3 line-clamp-2">{task.description}</p>
                      )}

                      {/* Source Email */}
                      {task.sourceSubject && (
                        <div className="flex items-center gap-2 text-sm text-slate-500 mb-3">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                          </svg>
                          <span className="truncate">
                            Von: {task.sourceSender} - {task.sourceSubject}
                          </span>
                        </div>
                      )}

                      {/* Meta */}
                      <div className="flex items-center gap-4 text-sm text-slate-500">
                        {task.deadline && (
                          <div className="flex items-center gap-1">
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                            </svg>
                            <span>
                              {new Date(task.deadline).toLocaleDateString('de-DE', {
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric',
                              })}
                            </span>
                          </div>
                        )}
                        <div className="flex items-center gap-1">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span>
                            Erstellt: {new Date(task.createdAt).toLocaleDateString('de-DE')}
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-2 ml-4">
                      {task.status === 'pending' && (
                        <button
                          onClick={() => updateTaskStatus(task.id, 'in_progress')}
                          className="px-3 py-1.5 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100"
                        >
                          Starten
                        </button>
                      )}
                      {task.status === 'in_progress' && (
                        <button
                          onClick={() => updateTaskStatus(task.id, 'completed')}
                          className="px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100"
                        >
                          Erledigen
                        </button>
                      )}
                      {task.status === 'completed' && (
                        <span className="px-3 py-1.5 text-sm font-medium text-green-700 bg-green-100 rounded-lg flex items-center gap-1">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                          </svg>
                          Erledigt
                        </span>
                      )}
                      <button className="p-2 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* Create Task Modal */}
      {showCreateModal && (
        <CreateTaskModal
          onClose={() => setShowCreateModal(false)}
          onSuccess={() => {
            setShowCreateModal(false)
            fetchTasks()
          }}
        />
      )}
    </div>
  )
}

function StatCard({
  label,
  value,
  color = 'slate',
  highlight = false
}: {
  label: string
  value: number
  color?: 'slate' | 'blue' | 'green' | 'yellow' | 'red' | 'orange'
  highlight?: boolean
}) {
  const colorClasses: Record<string, string> = {
    slate: 'text-slate-900',
    blue: 'text-blue-600',
    green: 'text-green-600',
    yellow: 'text-yellow-600',
    red: 'text-red-600',
    orange: 'text-orange-600',
  }

  return (
    <div className={`bg-white rounded-lg shadow p-4 ${highlight ? 'ring-2 ring-red-200' : ''}`}>
      <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">{label}</p>
      <p className={`text-2xl font-bold ${colorClasses[color]}`}>{value}</p>
    </div>
  )
}

function CreateTaskModal({
  onClose,
  onSuccess
}: {
  onClose: () => void
  onSuccess: () => void
}) {
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    priority: 'medium',
    deadline: '',
  })
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)

    try {
      const res = await fetch(`${API_BASE}/api/v1/mail/tasks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: formData.title,
          description: formData.description,
          priority: formData.priority,
          deadline: formData.deadline || null,
        }),
      })

      if (res.ok) {
        onSuccess()
      }
    } catch (err) {
      console.error('Failed to create task:', err)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div className="p-6 border-b border-slate-200">
          <h2 className="text-lg font-semibold text-slate-900">Neue Aufgabe erstellen</h2>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Titel</label>
            <input
              type="text"
              required
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              placeholder="Was muss erledigt werden?"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Beschreibung</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              rows={3}
              placeholder="Weitere Details..."
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Priorität</label>
              <select
                value={formData.priority}
                onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              >
                <option value="urgent">Dringend</option>
                <option value="high">Hoch</option>
                <option value="medium">Mittel</option>
                <option value="low">Niedrig</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Frist</label>
              <input
                type="date"
                value={formData.deadline}
                onChange={(e) => setFormData({ ...formData, deadline: e.target.value })}
                className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
              />
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-4 border-t border-slate-200">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100 rounded-lg"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 disabled:opacity-50"
            >
              {submitting ? 'Erstellen...' : 'Aufgabe erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
