'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { FolderOpen, ArrowLeft, Loader2, Sparkles } from 'lucide-react';
import Link from 'next/link';
import { LANGUAGE_OPTIONS, DATABASE_OPTIONS, type TargetLanguage, type TargetDatabase } from '@/lib/dark-factory/types/generation-options';

export default function NewProjectPage() {
  const router = useRouter();
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [language, setLanguage] = useState<TargetLanguage>('typescript-react');
  const [database, setDatabase] = useState<TargetDatabase>('postgresql');
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState('');

  const handleCreate = async () => {
    if (!name.trim()) { setError('Project name is required'); return; }
    setCreating(true);
    setError('');
    try {
      const res = await fetch('/api/dark-factory/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), description: description.trim() || null, targetLanguage: language, targetDatabase: database }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Failed to create project');
      }
      const project = await res.json();
      router.push(`/dark-factory/app`);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to create project');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <Link href="/dark-factory/app" className="inline-flex items-center gap-1 text-gray-400 hover:text-white transition-colors text-sm">
        <ArrowLeft className="w-4 h-4" /> Back to Dashboard
      </Link>

      <div>
        <h1 className="text-2xl font-bold text-white flex items-center gap-2">
          <FolderOpen className="w-6 h-6 text-sky-400" /> New Project
        </h1>
        <p className="text-gray-400 mt-1">Create a new The Hearth project to organize your generated code</p>
      </div>

      <div className="space-y-4 p-6 bg-white/5 border border-slate-700 rounded-xl">
        {/* Name */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">Project Name *</label>
          <input
            type="text"
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="e.g., Customer Portal, Inventory System"
            className="w-full px-3 py-2 bg-black/30 border border-slate-700 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:border-sky-500"
          />
        </div>

        {/* Description */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">Description</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="Brief description of what this project will generate..."
            rows={3}
            className="w-full px-3 py-2 bg-black/30 border border-slate-700 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:border-sky-500 resize-none"
          />
        </div>

        {/* Language */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">Target Language</label>
          <select
            value={language}
            onChange={e => setLanguage(e.target.value as TargetLanguage)}
            className="w-full px-3 py-2 bg-black/30 border border-slate-700 rounded-lg text-white focus:outline-none focus:border-sky-500"
          >
            {LANGUAGE_OPTIONS.map(opt => (
              <option key={opt.id} value={opt.id}>{opt.label}</option>
            ))}
          </select>
        </div>

        {/* Database */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">Target Database</label>
          <select
            value={database}
            onChange={e => setDatabase(e.target.value as TargetDatabase)}
            className="w-full px-3 py-2 bg-black/30 border border-slate-700 rounded-lg text-white focus:outline-none focus:border-sky-500"
          >
            {DATABASE_OPTIONS.map(opt => (
              <option key={opt.id} value={opt.id}>{opt.label}</option>
            ))}
          </select>
        </div>

        {error && <p className="text-red-400 text-sm">{error}</p>}

        <div className="flex gap-3 pt-2">
          <button
            onClick={handleCreate}
            disabled={creating}
            className="flex items-center gap-2 px-6 py-2.5 bg-sky-500 text-black rounded-lg font-medium hover:bg-sky-400 disabled:opacity-50 transition-colors"
          >
            {creating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
            {creating ? 'Creating...' : 'Create Project'}
          </button>
          <Link href="/dark-factory/app" className="px-6 py-2.5 text-gray-400 hover:text-white transition-colors">
            Cancel
          </Link>
        </div>
      </div>
    </div>
  );
}
