'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FolderOpen,
  Plus,
  ChevronDown,
  Archive,
  Clock,
  FileCode2,
  Loader2,
  Check,
  X,
  RotateCcw,
  Trash2,
} from 'lucide-react';
import { DarkFactoryProject, CreateProjectInput } from '@/lib/types/dark-factory';

interface ProjectSelectorProps {
  selectedProject: DarkFactoryProject | null;
  onProjectSelect: (project: DarkFactoryProject | null) => void;
  onProjectCreated?: (project: DarkFactoryProject) => void;
}

const PROJECT_COLORS = [
  '#0EA5E9', // cyan
  '#FDBA74', // purple
  '#10b981', // emerald
  '#f59e0b', // amber
  '#ef4444', // red
  '#ec4899', // pink
  '#3b82f6', // blue
  '#84cc16', // lime
];

export function ProjectSelector({
  selectedProject,
  onProjectSelect,
  onProjectCreated,
}: ProjectSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [projects, setProjects] = useState<DarkFactoryProject[]>([]);
  const [archivedProjects, setArchivedProjects] = useState<DarkFactoryProject[]>([]);
  const [loading, setLoading] = useState(true);
  const [showArchived, setShowArchived] = useState(false);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newProject, setNewProject] = useState<CreateProjectInput>({
    name: '',
    description: '',
    businessDomain: '',
    color: '#0EA5E9',
  });

  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      setLoading(true);
      const [activeRes, archivedRes] = await Promise.all([
        fetch('/api/dark-factory/projects?status=active'),
        fetch('/api/dark-factory/projects?status=archived'),
      ]);

      if (activeRes.ok) {
        const data = await activeRes.json();
        setProjects(data.projects || []);
      }
      if (archivedRes.ok) {
        const data = await archivedRes.json();
        setArchivedProjects(data.projects || []);
      }
    } catch (error) {
      console.error('Failed to fetch projects:', error);
    } finally {
      setLoading(false);
    }
  };

  const createProject = async () => {
    if (!newProject.name.trim()) return;

    try {
      setCreating(true);
      const res = await fetch('/api/dark-factory/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newProject),
      });

      if (res.ok) {
        const data = await res.json();
        setProjects([data.project, ...projects]);
        onProjectSelect(data.project);
        onProjectCreated?.(data.project);
        setShowCreateForm(false);
        setNewProject({ name: '', description: '', businessDomain: '', color: '#0EA5E9' });
        setIsOpen(false);
      }
    } catch (error) {
      console.error('Failed to create project:', error);
    } finally {
      setCreating(false);
    }
  };

  const archiveProject = async (projectId: string, archive: boolean) => {
    try {
      const res = await fetch(`/api/dark-factory/projects/${projectId}/archive`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ archive }),
      });

      if (res.ok) {
        await fetchProjects();
        if (selectedProject?.id === projectId) {
          onProjectSelect(null);
        }
      }
    } catch (error) {
      console.error('Failed to archive project:', error);
    }
  };

  const formatDate = (date: Date | string) => {
    const d = new Date(date);
    const now = new Date();
    const diff = now.getTime() - d.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) return 'Today';
    if (days === 1) return 'Yesterday';
    if (days < 7) return `${days} days ago`;
    if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
    return d.toLocaleDateString();
  };

  return (
    <div className="relative">
      {/* Selector Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-3 px-4 py-2.5 rounded-lg bg-slate-800/50 border border-slate-700/50 hover:border-brand-deep/50 transition-all min-w-[280px]"
      >
        {selectedProject ? (
          <>
            <div
              className="w-3 h-3 rounded-full"
              style={{ backgroundColor: selectedProject.color }}
            />
            <div className="flex-1 text-left">
              <div className="text-white font-medium">{selectedProject.name}</div>
              <div className="text-xs text-gray-400">
                {selectedProject.taskCount} tasks · {formatDate(selectedProject.lastActivityAt)}
              </div>
            </div>
          </>
        ) : (
          <>
            <FolderOpen className="w-5 h-5 text-gray-400" />
            <span className="text-gray-400">Select or Create Project</span>
          </>
        )}
        <ChevronDown
          className={`w-4 h-4 text-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`}
        />
      </button>

      {/* Dropdown */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="absolute top-full left-0 mt-2 w-[400px] bg-slate-900 border border-slate-700 rounded-xl shadow-2xl z-50 overflow-hidden"
          >
            {/* Create New Project */}
            {showCreateForm ? (
              <div className="p-4 border-b border-slate-700">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-white font-medium">New Project</span>
                  <button
                    onClick={() => setShowCreateForm(false)}
                    className="text-gray-400 hover:text-white"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <input
                  type="text"
                  value={newProject.name}
                  onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
                  placeholder="Project name *"
                  className="w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white placeholder-gray-500 mb-2 focus:outline-none focus:border-brand-deep"
                  autoFocus
                />

                <input
                  type="text"
                  value={newProject.description || ''}
                  onChange={(e) => setNewProject({ ...newProject, description: e.target.value })}
                  placeholder="Description (optional)"
                  className="w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white placeholder-gray-500 mb-2 focus:outline-none focus:border-brand-deep"
                />

                <input
                  type="text"
                  value={newProject.businessDomain || ''}
                  onChange={(e) => setNewProject({ ...newProject, businessDomain: e.target.value })}
                  placeholder="Business domain (e.g., e-commerce, healthcare)"
                  className="w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white placeholder-gray-500 mb-3 focus:outline-none focus:border-brand-deep"
                />

                {/* Color Picker */}
                <div className="flex items-center gap-2 mb-3">
                  <span className="text-gray-400 text-sm">Color:</span>
                  {PROJECT_COLORS.map((color) => (
                    <button
                      key={color}
                      onClick={() => setNewProject({ ...newProject, color })}
                      className={`w-6 h-6 rounded-full transition-transform ${
                        newProject.color === color ? 'ring-2 ring-white ring-offset-2 ring-offset-slate-900 scale-110' : ''
                      }`}
                      style={{ backgroundColor: color }}
                    />
                  ))}
                </div>

                <button
                  onClick={createProject}
                  disabled={!newProject.name.trim() || creating}
                  className="w-full py-2 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {creating ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Creating...
                    </>
                  ) : (
                    <>
                      <Check className="w-4 h-4" />
                      Create Project
                    </>
                  )}
                </button>
              </div>
            ) : (
              <button
                onClick={() => setShowCreateForm(true)}
                className="w-full px-4 py-3 flex items-center gap-3 text-brand hover:bg-slate-800/50 border-b border-slate-700"
              >
                <Plus className="w-5 h-5" />
                <span className="font-medium">New Project</span>
              </button>
            )}

            {/* Project List */}
            <div className="max-h-[300px] overflow-y-auto">
              {loading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-6 h-6 text-brand animate-spin" />
                </div>
              ) : projects.length === 0 && !showCreateForm ? (
                <div className="py-8 text-center text-gray-400">
                  <FolderOpen className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p>No projects yet</p>
                  <p className="text-sm">Create your first project to get started</p>
                </div>
              ) : (
                <>
                  {projects.map((project) => (
                    <div
                      key={project.id}
                      className={`group flex items-center gap-3 px-4 py-3 hover:bg-slate-800/50 cursor-pointer border-b border-slate-700/50 ${
                        selectedProject?.id === project.id ? 'bg-slate-800/70' : ''
                      }`}
                    >
                      <div
                        onClick={() => {
                          onProjectSelect(project);
                          setIsOpen(false);
                        }}
                        className="flex items-center gap-3 flex-1"
                      >
                        <div
                          className="w-3 h-3 rounded-full flex-shrink-0"
                          style={{ backgroundColor: project.color }}
                        />
                        <div className="flex-1 min-w-0">
                          <div className="text-white font-medium truncate">{project.name}</div>
                          <div className="flex items-center gap-3 text-xs text-gray-400">
                            <span className="flex items-center gap-1">
                              <FileCode2 className="w-3 h-3" />
                              {project.taskCount} tasks
                            </span>
                            <span className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {formatDate(project.lastActivityAt)}
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Archive button */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          archiveProject(project.id, true);
                        }}
                        className="opacity-0 group-hover:opacity-100 p-1.5 text-gray-400 hover:text-amber-400 hover:bg-amber-400/10 rounded transition-all"
                        title="Archive project"
                      >
                        <Archive className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </>
              )}
            </div>

            {/* Archived Section */}
            {archivedProjects.length > 0 && (
              <div className="border-t border-slate-700">
                <button
                  onClick={() => setShowArchived(!showArchived)}
                  className="w-full px-4 py-2 flex items-center gap-2 text-gray-400 hover:text-white hover:bg-slate-800/50"
                >
                  <Archive className="w-4 h-4" />
                  <span className="text-sm">Archived ({archivedProjects.length})</span>
                  <ChevronDown
                    className={`w-4 h-4 ml-auto transition-transform ${showArchived ? 'rotate-180' : ''}`}
                  />
                </button>

                <AnimatePresence>
                  {showArchived && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      className="overflow-hidden"
                    >
                      {archivedProjects.map((project) => (
                        <div
                          key={project.id}
                          className="group flex items-center gap-3 px-4 py-2 hover:bg-slate-800/50 opacity-60 hover:opacity-100"
                        >
                          <div
                            className="w-3 h-3 rounded-full flex-shrink-0"
                            style={{ backgroundColor: project.color }}
                          />
                          <span className="text-gray-300 flex-1 truncate">{project.name}</span>
                          <button
                            onClick={() => archiveProject(project.id, false)}
                            className="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-brand"
                            title="Restore project"
                          >
                            <RotateCcw className="w-4 h-4" />
                          </button>
                        </div>
                      ))}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>

      {/* Click outside to close */}
      {isOpen && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => setIsOpen(false)}
        />
      )}
    </div>
  );
}
