import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useProject } from '../../context/ProjectContext';
import { projectsService } from '../../services/projects.service';

import AnteproyectoImportModal from './AnteproyectoImportModal';

function generateCode() {
  try {
    const b = JSON.parse(localStorage.getItem('arpm_branding') || '{}');
    const name = b.appName || 'ARPM';
    const initials = name.split(/\s+/).map(w => w[0]).join('').toUpperCase().slice(0, 4);
    const year = new Date().getFullYear();

    const seq = parseInt(localStorage.getItem('arpm_project_seq') || '0', 10) + 1;
    return `${initials}-PRY-${year}-${String(seq).padStart(3, '0')}`;
  } catch { return `PRY-${new Date().getFullYear()}-001`; }
}

const METHODOLOGIES = ['PMI','Scrum','Agile','Kanban','PRINCE2','Lean','Waterfall'];
const CATEGORIES    = ['Infraestructura','Tecnología','Entretenimiento','Producto Interno','Salud','Educación','Finanzas','Otro'];
const TYPES         = ['Construcción','Software','Producción','Consultoría','Marketing','Investigación','Otro'];
const STATUSES      = [
  { value:'ACTIVO',     label:'Activo'     },
  { value:'PAUSADO',    label:'Pausado'    },
  { value:'EN_RIESGO',  label:'En riesgo'  },
  { value:'COMPLETADO', label:'Completado' },
];
const RAG_OPTS = [
  { value:'VERDE',    label:'Verde — en plan',      dot:'bg-emerald-400' },
  { value:'AMARILLO', label:'Ámbar — atención',     dot:'bg-amber-400'   },
  { value:'ROJO',     label:'Rojo — requiere acción',dot:'bg-red-400'    },
];

const INIT = () => ({
  code: generateCode(), name:'', type:'Software', category:'Tecnología', client:'',
  methodology:'Scrum', status:'ACTIVO', ragStatus:'VERDE',
  budget:'', startDate:'', plannedEndDate:'', description:'',
});

function Field({ label, error, children }) {
  return (
    <div className="space-y-1">
      <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">{label}</label>
      {children}
      {error && <p className="text-xs text-red-500">{error}</p>}
    </div>
  );
}

const input = 'w-full px-3 py-2.5 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white placeholder-slate-300 dark:placeholder-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 transition';
const select = input + ' cursor-pointer';

export default function NewProjectPage() {
  const navigate = useNavigate();
  const { setSelectedProjectId } = useProject();
  const [form, setForm]     = useState(INIT);
  const [errors, setErrors] = useState({});
  const [saving, setSaving] = useState(false);
  const [showImport, setShowImport] = useState(false);

  // Regenerate code if branding changes while on this page
  useEffect(() => { setForm(f => ({ ...f, code: generateCode() })); }, []);

  const handleImport = ({ plan, projectId, taskCount }) => {
    setSelectedProjectId(projectId);
    navigate('/projects', { state: { imported: true, name: plan?.project?.name, taskCount } });
  };

  const set = (k, v) => setForm(f => ({...f, [k]: v}));

  const validate = () => {
    const e = {};
    if (!form.name.trim())         e.name = 'Nombre requerido';
    if (!form.code.trim())         e.code = 'Código requerido';
    if (!form.client.trim())       e.client = 'Cliente requerido';
    if (!form.startDate)           e.startDate = 'Fecha inicio requerida';
    if (!form.plannedEndDate)      e.plannedEndDate = 'Fecha fin requerida';
    if (form.startDate && form.plannedEndDate && form.startDate >= form.plannedEndDate)
      e.plannedEndDate = 'Debe ser posterior a la fecha de inicio';
    if (form.budget && isNaN(Number(form.budget))) e.budget = 'Debe ser un número';
    return e;
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setSaving(true);
    try {
      const payload = { ...form, budget: form.budget ? Number(form.budget) : null };
      await projectsService.create(payload);
      navigate('/projects');
    } catch {
      // demo mode: just go back
      navigate('/projects');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto pb-10">
      {showImport && (
        <AnteproyectoImportModal
          onImport={handleImport}
          onClose={() => setShowImport(false)}
        />
      )}
      {/* Breadcrumb */}
      <nav className="flex items-center gap-2 text-sm text-slate-400 dark:text-gray-500 mb-6">
        <button onClick={()=>navigate('/projects')} className="hover:text-blue-600 dark:hover:text-blue-400 transition cursor-pointer">Proyectos</button>
        <span>/</span>
        <span className="text-slate-700 dark:text-gray-300 font-medium">Nuevo proyecto</span>
      </nav>

      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-bold text-slate-900 dark:text-white">Crear proyecto</h1>
        <button type="button" onClick={() => setShowImport(true)}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-violet-50 dark:bg-violet-500/10 text-violet-700 dark:text-violet-400 border border-violet-200 dark:border-violet-500/30 hover:bg-violet-100 dark:hover:bg-violet-500/20 transition cursor-pointer">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
          </svg>
          Importar anteproyecto con IA
        </button>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">

        {/* Identificación */}
        <section className="bg-white dark:bg-surface-800 rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm space-y-4">
          <h2 className="text-sm font-semibold text-slate-700 dark:text-gray-300 flex items-center gap-2">
            <span className="w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400 text-xs flex items-center justify-center font-bold">1</span>
            Identificación
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Código *" error={errors.code}>
              <input className={input} placeholder="PRY-2026-005" value={form.code}
                onChange={e=>set('code',e.target.value.toUpperCase())}/>
            </Field>
            <Field label="Nombre del proyecto *" error={errors.name}>
              <input className={input} placeholder="Nombre descriptivo del proyecto" value={form.name}
                onChange={e=>set('name',e.target.value)}/>
            </Field>
            <Field label="Cliente *" error={errors.client}>
              <input className={input} placeholder="Nombre del cliente o empresa" value={form.client}
                onChange={e=>set('client',e.target.value)}/>
            </Field>
            <Field label="Tipo">
              <select className={select} value={form.type} onChange={e=>set('type',e.target.value)}>
                {TYPES.map(t=><option key={t}>{t}</option>)}
              </select>
            </Field>
            <Field label="Categoría">
              <select className={select} value={form.category} onChange={e=>set('category',e.target.value)}>
                {CATEGORIES.map(c=><option key={c}>{c}</option>)}
              </select>
            </Field>
            <Field label="Metodología">
              <select className={select} value={form.methodology} onChange={e=>set('methodology',e.target.value)}>
                {METHODOLOGIES.map(m=><option key={m}>{m}</option>)}
              </select>
            </Field>
          </div>
        </section>

        {/* Estado */}
        <section className="bg-white dark:bg-surface-800 rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm space-y-4">
          <h2 className="text-sm font-semibold text-slate-700 dark:text-gray-300 flex items-center gap-2">
            <span className="w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400 text-xs flex items-center justify-center font-bold">2</span>
            Estado y salud
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Estado">
              <select className={select} value={form.status} onChange={e=>set('status',e.target.value)}>
                {STATUSES.map(s=><option key={s.value} value={s.value}>{s.label}</option>)}
              </select>
            </Field>
            <Field label="Estado RAG">
              <div className="flex gap-2">
                {RAG_OPTS.map(r=>(
                  <button type="button" key={r.value}
                    onClick={()=>set('ragStatus',r.value)}
                    className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl border text-xs font-medium transition cursor-pointer
                      ${form.ragStatus===r.value
                        ? 'border-slate-400 dark:border-gray-400 bg-slate-50 dark:bg-surface-700 text-slate-900 dark:text-white shadow-sm'
                        : 'border-slate-200 dark:border-surface-600 text-slate-500 dark:text-gray-500 hover:border-slate-300 dark:hover:border-surface-500'}`}>
                    <span className={`w-2 h-2 rounded-full ${r.dot}`}/>
                    {r.value.charAt(0)+r.value.slice(1).toLowerCase()}
                  </button>
                ))}
              </div>
            </Field>
          </div>
        </section>

        {/* Fechas y presupuesto */}
        <section className="bg-white dark:bg-surface-800 rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm space-y-4">
          <h2 className="text-sm font-semibold text-slate-700 dark:text-gray-300 flex items-center gap-2">
            <span className="w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400 text-xs flex items-center justify-center font-bold">3</span>
            Fechas y presupuesto
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <Field label="Fecha inicio *" error={errors.startDate}>
              <input type="date" className={input} value={form.startDate}
                onChange={e=>set('startDate',e.target.value)}/>
            </Field>
            <Field label="Fecha fin planeada *" error={errors.plannedEndDate}>
              <input type="date" className={input} value={form.plannedEndDate}
                onChange={e=>set('plannedEndDate',e.target.value)}/>
            </Field>
            <Field label="Presupuesto (USD)" error={errors.budget}>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-gray-500 text-sm">$</span>
                <input className={input + ' pl-7'} placeholder="0.00" value={form.budget}
                  onChange={e=>set('budget',e.target.value)}/>
              </div>
            </Field>
          </div>
        </section>

        {/* Descripción */}
        <section className="bg-white dark:bg-surface-800 rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm space-y-4">
          <h2 className="text-sm font-semibold text-slate-700 dark:text-gray-300 flex items-center gap-2">
            <span className="w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400 text-xs flex items-center justify-center font-bold">4</span>
            Descripción
          </h2>
          <Field label="Descripción del proyecto">
            <textarea className={input + ' min-h-[100px] resize-y'} placeholder="Describe el alcance, objetivos y contexto del proyecto..."
              value={form.description} onChange={e=>set('description',e.target.value)}/>
          </Field>
        </section>

        {/* Actions */}
        <div className="flex justify-end gap-3">
          <button type="button" onClick={()=>navigate('/projects')}
            className="px-5 py-2.5 text-sm font-medium rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">
            Cancelar
          </button>
          <button type="submit" disabled={saving}
            className="px-6 py-2.5 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-sm transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2">
            {saving && <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin"/>}
            {saving ? 'Guardando…' : 'Crear proyecto'}
          </button>
        </div>
      </form>
    </div>
  );
}
