'use client';

/**
 * Demo Task List - Generated by ${VOCAB.factory}
 * This demonstrates a working app created by the ${VOCAB.factory} system.
 * Uses localStorage for persistence (no database required for demo).
 */

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Plus,
  Filter,
  SortAsc,
  SortDesc,
  Calendar,
  AlertCircle,
  CheckCircle2,
  Circle,
  Trash2,
  Edit3,
  Clock,
  Flag,
  ArrowLeft,
  Bug,
  X,
  Save,
  Loader2,
  Search
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';
import { VOCAB } from '@/lib/white-label/constants';

interface Task {
  id: string;
  title: string;
  description: string;
  completed: boolean;
  priority: 'low' | 'medium' | 'high';
  dueDate: string;
  createdAt: string;
  updatedAt: string;
}

type FilterType = 'all' | 'completed' | 'pending';
type SortType = 'date' | 'priority' | 'title';

const STORAGE_KEY = 'gfs-demo-tasks';

// Generate unique ID
const generateId = () => `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

// Priority colors
const priorityColors = {
  low: 'bg-green-500/20 text-green-400 border-green-500/30',
  medium: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
  high: 'bg-red-500/20 text-red-400 border-red-500/30',
};

const priorityIcons = {
  low: <Flag className="w-3 h-3" />,
  medium: <Flag className="w-3 h-3" />,
  high: <AlertCircle className="w-3 h-3" />,
};

export default function DemoTasksPage() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [filter, setFilter] = useState<FilterType>('all');
  const [sortBy, setSortBy] = useState<SortType>('date');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [searchQuery, setSearchQuery] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [loading, setLoading] = useState(true);

  // Form state
  const [formTitle, setFormTitle] = useState('');
  const [formDescription, setFormDescription] = useState('');
  const [formPriority, setFormPriority] = useState<'low' | 'medium' | 'high'>('medium');
  const [formDueDate, setFormDueDate] = useState('');

  // Load tasks from localStorage
  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      try {
        setTasks(JSON.parse(stored));
      } catch (e) {
        console.error('Failed to parse tasks:', e);
      }
    } else {
      // Add some demo tasks
      const demoTasks: Task[] = [
        {
          id: generateId(),
          title: `Review ${VOCAB.factory} architecture`,
          description: 'Analyze the code generation pipeline and suggest improvements',
          completed: false,
          priority: 'high',
          dueDate: new Date(Date.now() + 86400000).toISOString().split('T')[0],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: generateId(),
          title: 'Test Tes podcast audio',
          description: 'Listen to the HeyGen output and provide feedback',
          completed: true,
          priority: 'medium',
          dueDate: new Date().toISOString().split('T')[0],
          createdAt: new Date(Date.now() - 86400000).toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: generateId(),
          title: 'Update FF documentation',
          description: `Add ${VOCAB.factory} deployment guide`,
          completed: false,
          priority: 'low',
          dueDate: new Date(Date.now() + 86400000 * 7).toISOString().split('T')[0],
          createdAt: new Date(Date.now() - 172800000).toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      setTasks(demoTasks);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(demoTasks));
    }
    setLoading(false);
  }, []);

  // Save tasks to localStorage
  const saveTasks = (newTasks: Task[]) => {
    setTasks(newTasks);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newTasks));
  };

  // Add or update task
  const handleSaveTask = () => {
    if (!formTitle.trim()) return;

    const now = new Date().toISOString();

    if (editingTask) {
      // Update existing
      const updated = tasks.map(t =>
        t.id === editingTask.id
          ? {
              ...t,
              title: formTitle,
              description: formDescription,
              priority: formPriority,
              dueDate: formDueDate,
              updatedAt: now,
            }
          : t
      );
      saveTasks(updated);
    } else {
      // Add new
      const newTask: Task = {
        id: generateId(),
        title: formTitle,
        description: formDescription,
        priority: formPriority,
        dueDate: formDueDate,
        completed: false,
        createdAt: now,
        updatedAt: now,
      };
      saveTasks([newTask, ...tasks]);
    }

    resetForm();
  };

  // Toggle task completion
  const toggleComplete = (id: string) => {
    const updated = tasks.map(t =>
      t.id === id ? { ...t, completed: !t.completed, updatedAt: new Date().toISOString() } : t
    );
    saveTasks(updated);
  };

  // Delete task
  const deleteTask = (id: string) => {
    saveTasks(tasks.filter(t => t.id !== id));
  };

  // Edit task
  const startEdit = (task: Task) => {
    setEditingTask(task);
    setFormTitle(task.title);
    setFormDescription(task.description);
    setFormPriority(task.priority);
    setFormDueDate(task.dueDate);
    setShowForm(true);
  };

  // Reset form
  const resetForm = () => {
    setShowForm(false);
    setEditingTask(null);
    setFormTitle('');
    setFormDescription('');
    setFormPriority('medium');
    setFormDueDate('');
  };

  // Filter and sort tasks
  const filteredTasks = tasks
    .filter(t => {
      if (filter === 'completed') return t.completed;
      if (filter === 'pending') return !t.completed;
      return true;
    })
    .filter(t => {
      if (!searchQuery) return true;
      const q = searchQuery.toLowerCase();
      return t.title.toLowerCase().includes(q) || t.description.toLowerCase().includes(q);
    })
    .sort((a, b) => {
      let cmp = 0;
      switch (sortBy) {
        case 'date':
          cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
          break;
        case 'priority':
          const pOrder = { high: 3, medium: 2, low: 1 };
          cmp = pOrder[a.priority] - pOrder[b.priority];
          break;
        case 'title':
          cmp = a.title.localeCompare(b.title);
          break;
      }
      return sortDir === 'asc' ? cmp : -cmp;
    });

  const stats = {
    total: tasks.length,
    completed: tasks.filter(t => t.completed).length,
    pending: tasks.filter(t => !t.completed).length,
    highPriority: tasks.filter(t => t.priority === 'high' && !t.completed).length,
  };

  return (
    <>
      <InternalHeader />
      <div className="min-h-screen bg-brand-bg pt-16">
        {/* Header */}
        <div className="border-b border-white/10 bg-white/5">
          <div className="max-w-7xl mx-auto px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link
                href="/ghost-control/dark-factory"
                className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
              >
                <ArrowLeft className="w-4 h-4" />
                <span className="text-sm">{VOCAB.factory}</span>
              </Link>
              <span className="text-gray-600">|</span>
              <h1 className="text-white font-medium">Task List</h1>
              <span className="px-2 py-0.5 text-xs bg-green-500/20 text-green-400 rounded-full">Demo</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-gray-500">
              <span className="px-2 py-1 bg-brand-secondary/20 text-brand-secondary-light rounded">Generated by {VOCAB.factory}</span>
            </div>
          </div>
        </div>

        <div className="max-w-6xl mx-auto px-4 py-6">
          {/* Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div className="glass-card p-4 border border-white/10">
              <div className="text-2xl font-bold text-white">{stats.total}</div>
              <div className="text-sm text-gray-400">Total Tasks</div>
            </div>
            <div className="glass-card p-4 border border-white/10">
              <div className="text-2xl font-bold text-green-400">{stats.completed}</div>
              <div className="text-sm text-gray-400">Completed</div>
            </div>
            <div className="glass-card p-4 border border-white/10">
              <div className="text-2xl font-bold text-amber-400">{stats.pending}</div>
              <div className="text-sm text-gray-400">Pending</div>
            </div>
            <div className="glass-card p-4 border border-white/10">
              <div className="text-2xl font-bold text-red-400">{stats.highPriority}</div>
              <div className="text-sm text-gray-400">High Priority</div>
            </div>
          </div>

          {/* Toolbar */}
          <div className="flex flex-wrap items-center gap-3 mb-6">
            <button
              onClick={() => {
                resetForm();
                setShowForm(true);
              }}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity"
            >
              <Plus className="w-4 h-4" />
              Add Task
            </button>

            <div className="relative flex-1 max-w-xs">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
              <input
                type="text"
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Search tasks..."
                className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
              />
            </div>

            <div className="flex items-center gap-2">
              <Filter className="w-4 h-4 text-gray-500" />
              <select
                value={filter}
                onChange={e => setFilter(e.target.value as FilterType)}
                className="bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-brand-deep/50"
              >
                <option value="all">All</option>
                <option value="pending">Pending</option>
                <option value="completed">Completed</option>
              </select>
            </div>

            <div className="flex items-center gap-2">
              <select
                value={sortBy}
                onChange={e => setSortBy(e.target.value as SortType)}
                className="bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-brand-deep/50"
              >
                <option value="date">Date</option>
                <option value="priority">Priority</option>
                <option value="title">Title</option>
              </select>
              <button
                onClick={() => setSortDir(d => (d === 'asc' ? 'desc' : 'asc'))}
                className="p-2 bg-white/5 border border-white/10 rounded-lg text-gray-400 hover:text-white transition-colors"
              >
                {sortDir === 'asc' ? <SortAsc className="w-4 h-4" /> : <SortDesc className="w-4 h-4" />}
              </button>
            </div>
          </div>

          {/* Task Form Modal */}
          {showForm && (
            <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
              <div className="glass-card border border-white/20 w-full max-w-lg p-6 rounded-xl">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-white">
                    {editingTask ? 'Edit Task' : 'New Task'}
                  </h3>
                  <button
                    onClick={resetForm}
                    className="text-gray-400 hover:text-white transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Title *</label>
                    <input
                      type="text"
                      value={formTitle}
                      onChange={e => setFormTitle(e.target.value)}
                      placeholder="Task title..."
                      className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
                      autoFocus
                    />
                  </div>

                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Description</label>
                    <textarea
                      value={formDescription}
                      onChange={e => setFormDescription(e.target.value)}
                      placeholder="Task description..."
                      rows={3}
                      className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50 resize-none"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Priority</label>
                      <select
                        value={formPriority}
                        onChange={e => setFormPriority(e.target.value as 'low' | 'medium' | 'high')}
                        className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                      >
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Due Date</label>
                      <input
                        type="date"
                        value={formDueDate}
                        onChange={e => setFormDueDate(e.target.value)}
                        className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                      />
                    </div>
                  </div>

                  <div className="flex justify-end gap-3 pt-2">
                    <button
                      onClick={resetForm}
                      className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleSaveTask}
                      disabled={!formTitle.trim()}
                      className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Save className="w-4 h-4" />
                      {editingTask ? 'Update' : 'Create'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Task List */}
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 text-brand animate-spin" />
            </div>
          ) : filteredTasks.length === 0 ? (
            <div className="glass-card border border-white/10 p-12 text-center">
              <Circle className="w-12 h-12 text-gray-600 mx-auto mb-4" />
              <h3 className="text-lg text-white mb-2">No tasks found</h3>
              <p className="text-gray-500 mb-4">
                {filter !== 'all' || searchQuery
                  ? 'Try adjusting your filters'
                  : 'Create your first task to get started'}
              </p>
              <button
                onClick={() => {
                  resetForm();
                  setShowForm(true);
                }}
                className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity"
              >
                <Plus className="w-4 h-4" />
                Add Task
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {filteredTasks.map(task => (
                <div
                  key={task.id}
                  className={`glass-card border p-4 rounded-lg transition-all ${
                    task.completed
                      ? 'border-white/5 opacity-60'
                      : 'border-white/10 hover:border-white/20'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {/* Checkbox */}
                    <button
                      onClick={() => toggleComplete(task.id)}
                      className={`mt-1 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors ${
                        task.completed
                          ? 'bg-green-500 border-green-500 text-white'
                          : 'border-gray-500 hover:border-brand-deep'
                      }`}
                    >
                      {task.completed && <CheckCircle2 className="w-3 h-3" />}
                    </button>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h4
                          className={`text-white font-medium ${
                            task.completed ? 'line-through text-gray-500' : ''
                          }`}
                        >
                          {task.title}
                        </h4>
                        <span
                          className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full border ${
                            priorityColors[task.priority]
                          }`}
                        >
                          {priorityIcons[task.priority]}
                          {task.priority}
                        </span>
                      </div>
                      {task.description && (
                        <p className="text-sm text-gray-400 mb-2">{task.description}</p>
                      )}
                      <div className="flex items-center gap-4 text-xs text-gray-500">
                        {task.dueDate && (
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {new Date(task.dueDate).toLocaleDateString()}
                          </span>
                        )}
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {new Date(task.createdAt).toLocaleDateString()}
                        </span>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => startEdit(task)}
                        className="p-2 text-gray-500 hover:text-brand hover:bg-white/5 rounded-lg transition-colors"
                        title="Edit"
                      >
                        <Edit3 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => deleteTask(task.id)}
                        className="p-2 text-gray-500 hover:text-red-400 hover:bg-white/5 rounded-lg transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
