import React, { useState } from 'react'
import { ContractTemplate } from '../types'
import { TemplateEditor } from '../components/templates/TemplateEditor'

// Default built-in templates
const DEFAULT_TEMPLATES: ContractTemplate[] = [
  {
    id: 'simple',
    name: 'Simple',
    description: 'A simple contract with plan and execute phases.',
    isBuiltIn: true,
    phases: [
      {
        id: 'plan',
        name: 'Plan',
        deliverables: [{ id: 'plan-deliverable', name: 'Plan' }]
      },
      {
        id: 'execute',
        name: 'Execute',
        deliverables: [{ id: 'pr-deliverable', name: 'PR' }]
      }
    ]
  },
  {
    id: 'specification',
    name: 'Specification',
    description: 'A comprehensive contract with research, specification, planning, execution, and review phases.',
    isBuiltIn: true,
    phases: [
      {
        id: 'research',
        name: 'Research',
        deliverables: [{ id: 'research-notes', name: 'Research Notes' }]
      },
      {
        id: 'specify',
        name: 'Specify',
        deliverables: [{ id: 'requirements', name: 'Requirements' }]
      },
      {
        id: 'plan',
        name: 'Plan',
        deliverables: [{ id: 'plan-deliverable', name: 'Plan' }]
      },
      {
        id: 'execute',
        name: 'Execute',
        deliverables: [{ id: 'pr-deliverable', name: 'PR' }]
      },
      {
        id: 'review',
        name: 'Review',
        deliverables: [{ id: 'release-notes', name: 'Release Notes' }]
      }
    ]
  },
  {
    id: 'execute',
    name: 'Execute',
    description: 'A minimal contract with only an execute phase and no deliverables.',
    isBuiltIn: true,
    phases: [
      {
        id: 'execute',
        name: 'Execute',
        deliverables: []
      }
    ]
  }
]

type Props = {
  onClose: () => void
}

export const TemplatesPage: React.FC<Props> = ({ onClose }) => {
  const [templates, setTemplates] = useState<ContractTemplate[]>(() => {
    const saved = localStorage.getItem('contractTemplates')
    if (saved) {
      try {
        return JSON.parse(saved)
      } catch {
        return DEFAULT_TEMPLATES
      }
    }
    return DEFAULT_TEMPLATES
  })

  const [editingTemplate, setEditingTemplate] = useState<ContractTemplate | null>(null)
  const [showNewTemplateForm, setShowNewTemplateForm] = useState(false)
  const [newTemplateName, setNewTemplateName] = useState('')
  const [newTemplateDescription, setNewTemplateDescription] = useState('')

  const saveTemplates = (newTemplates: ContractTemplate[]) => {
    setTemplates(newTemplates)
    localStorage.setItem('contractTemplates', JSON.stringify(newTemplates))
  }

  const handleSaveTemplate = (updatedTemplate: ContractTemplate) => {
    const newTemplates = templates.map(t =>
      t.id === updatedTemplate.id ? updatedTemplate : t
    )
    saveTemplates(newTemplates)
    setEditingTemplate(null)
  }

  const handleCreateTemplate = () => {
    if (!newTemplateName.trim()) return

    const newTemplate: ContractTemplate = {
      id: `custom-${Date.now()}`,
      name: newTemplateName.trim(),
      description: newTemplateDescription.trim() || 'Custom contract template',
      isBuiltIn: false,
      phases: [
        {
          id: `phase-${Date.now()}`,
          name: 'Execute',
          deliverables: []
        }
      ]
    }

    saveTemplates([...templates, newTemplate])
    setNewTemplateName('')
    setNewTemplateDescription('')
    setShowNewTemplateForm(false)
  }

  const handleDeleteTemplate = (templateId: string) => {
    const template = templates.find(t => t.id === templateId)
    if (template?.isBuiltIn) return

    if (window.confirm(`Are you sure you want to delete "${template?.name}"?`)) {
      saveTemplates(templates.filter(t => t.id !== templateId))
    }
  }

  const handleResetToDefaults = () => {
    if (window.confirm('Reset all templates to defaults? This will remove any custom templates.')) {
      saveTemplates(DEFAULT_TEMPLATES)
    }
  }

  if (editingTemplate) {
    return (
      <div className="templates-page">
        <TemplateEditor
          template={editingTemplate}
          onSave={handleSaveTemplate}
          onCancel={() => setEditingTemplate(null)}
        />
      </div>
    )
  }

  return (
    <div className="templates-page">
      <div className="templates-header">
        <div className="templates-header-left">
          <h1 className="templates-title">Contract Templates</h1>
          <p className="templates-subtitle">Manage contract types and their phase deliverables</p>
        </div>
        <div className="templates-header-right">
          <button className="templates-btn secondary" onClick={handleResetToDefaults}>
            Reset to Defaults
          </button>
          <button className="templates-btn primary" onClick={() => setShowNewTemplateForm(true)}>
            + New Template
          </button>
          <button className="templates-close-btn" onClick={onClose}>
            x
          </button>
        </div>
      </div>

      {showNewTemplateForm && (
        <div className="new-template-form">
          <div className="form-row">
            <input
              type="text"
              className="form-input"
              placeholder="Template name..."
              value={newTemplateName}
              onChange={(e) => setNewTemplateName(e.target.value)}
            />
            <input
              type="text"
              className="form-input"
              placeholder="Description (optional)..."
              value={newTemplateDescription}
              onChange={(e) => setNewTemplateDescription(e.target.value)}
            />
            <button className="templates-btn primary" onClick={handleCreateTemplate}>
              Create
            </button>
            <button className="templates-btn secondary" onClick={() => setShowNewTemplateForm(false)}>
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="templates-grid">
        {templates.map(template => (
          <div key={template.id} className={`template-card ${template.isBuiltIn ? 'built-in' : 'custom'}`}>
            <div className="template-card-header">
              <h3 className="template-card-title">{template.name}</h3>
              {template.isBuiltIn && <span className="template-badge">Built-in</span>}
              {!template.isBuiltIn && <span className="template-badge custom">Custom</span>}
            </div>
            <p className="template-card-description">{template.description}</p>

            <div className="template-phases">
              {template.phases.map((phase, index) => (
                <div key={phase.id} className="template-phase">
                  <div className="phase-indicator">
                    <span className="phase-dot"></span>
                    {index < template.phases.length - 1 && <span className="phase-line"></span>}
                  </div>
                  <div className="phase-content">
                    <span className="phase-name">{phase.name}</span>
                    <span className="phase-deliverables">
                      {phase.deliverables.length === 0
                        ? '(no deliverables)'
                        : phase.deliverables.map(d => d.name).join(', ')}
                    </span>
                  </div>
                </div>
              ))}
            </div>

            <div className="template-card-actions">
              <button
                className="template-action-btn edit"
                onClick={() => setEditingTemplate(template)}
              >
                Edit
              </button>
              {!template.isBuiltIn && (
                <button
                  className="template-action-btn delete"
                  onClick={() => handleDeleteTemplate(template.id)}
                >
                  Delete
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
