'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ChevronLeft, MessageSquare, AlertCircle, Users } from 'lucide-react'
import { addHours } from 'date-fns'

import { Card, Button, showToast } from '@/components/ui'
import { Header, PageContainer } from '@/components/layout/header'
import { useApp } from '../../provider'

const CATEGORIES = [
  { value: 'GENERAL', label: 'General Update', emoji: '📝', color: 'bg-blue-100 border-blue-200' },
  { value: 'SYMPTOM', label: 'Symptom Observation', emoji: '😷', color: 'bg-red-50 border-red-200' },
  { value: 'MEDICATION', label: 'Medication Note', emoji: '💊', color: 'bg-green-50 border-green-200' },
  { value: 'MOOD', label: 'Mood/Energy', emoji: '💭', color: 'bg-purple-50 border-purple-200' },
]

const PRIORITIES = [
  { value: 'LOW', label: 'FYI Only' },
  { value: 'NORMAL', label: 'Normal' },
  { value: 'HIGH', label: 'Important - Please Read', color: 'text-red-600' },
]

export default function NewHandoffNotePage() {
  const router = useRouter()
  const { currentWorkspace } = useApp()
  const [content, setContent] = useState('')
  const [category, setCategory] = useState('GENERAL')
  const [priority, setPriority] = useState('NORMAL')
  const [expiresIn, setExpiresIn] = useState('12')
  const [saving, setSaving] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!content.trim()) {
      showToast('Please write a note', 'error')
      return
    }

    setSaving(true)
    try {
      const expiresAt = addHours(new Date(), parseInt(expiresIn))
      
      const response = await fetch(`/api/workspaces/${currentWorkspace.id}/handoff-notes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: content.trim(),
          category,
          priority,
          expiresAt: expiresAt.toISOString(),
        }),
      })

      if (!response.ok) throw new Error('Failed to create note')

      showToast('Handoff note added!', 'success')
      router.push('/care')
    } catch {
      showToast('Failed to add note', 'error')
    } finally {
      setSaving(false)
    }
  }

  return (
    <>
      <Header 
        title="Handoff Note"
        leftAction={{
          icon: <ChevronLeft className="w-6 h-6" />,
          label: 'Back',
          onClick: () => router.push('/care')
        }}
      />
      <PageContainer className="pt-4">
        {/* Info Card */}
        <Card className="bg-amber-50 border-amber-200 mb-4">
          <div className="flex items-start gap-3">
            <Users className="w-5 h-5 text-amber-600 mt-0.5" />
            <div>
              <h3 className="font-medium text-amber-900">What are handoff notes?</h3>
              <p className="text-sm text-amber-700 mt-1">
                Use these to communicate with other caregivers. They expire after a set time and can be marked as read.
              </p>
            </div>
          </div>
        </Card>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Category */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              What type of note?
            </label>
            <div className="space-y-2">
              {CATEGORIES.map((cat) => (
                <button
                  key={cat.value}
                  type="button"
                  onClick={() => setCategory(cat.value)}
                  className={`w-full p-3 rounded-lg border-2 text-left transition-all flex items-center gap-3 ${
                    category === cat.value
                      ? cat.color + ' border-current'
                      : 'border-border hover:border-secondary-300'
                  }`}
                >
                  <span className="text-2xl">{cat.emoji}</span>
                  <span className="font-medium text-secondary-900">{cat.label}</span>
                </button>
              ))}
            </div>
          </Card>

          {/* Priority */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              <AlertCircle className="w-4 h-4 inline mr-1" />
              Priority
            </label>
            <select
              value={priority}
              onChange={(e) => setPriority(e.target.value)}
              className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
            >
              {PRIORITIES.map((p) => (
                <option key={p.value} value={p.value} className={p.color}>
                  {p.label}
                </option>
              ))}
            </select>
          </Card>

          {/* Content */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              <MessageSquare className="w-4 h-4 inline mr-1" />
              Your Note
            </label>
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="What should other caregivers know? For example:\n• Patient seemed more tired than usual today\n• New medication started, watching for side effects\n• Appointment went well, next one scheduled for..."
              rows={5}
              className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500 resize-none"
              required
            />
          </Card>

          {/* Expires In */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              Note expires in
            </label>
            <div className="flex gap-2">
              {['4', '12', '24', '48'].map((hours) => (
                <button
                  key={hours}
                  type="button"
                  onClick={() => setExpiresIn(hours)}
                  className={`flex-1 py-2 rounded-lg border-2 text-sm font-medium transition-all ${
                    expiresIn === hours
                      ? 'border-primary-500 bg-primary-50 text-primary-700'
                      : 'border-border hover:border-secondary-300 text-secondary-600'
                  }`}
                >
                  {hours}h
                </button>
              ))}
            </div>
            <p className="text-xs text-secondary-500 mt-2">
              Notes expire automatically to keep information fresh
            </p>
          </Card>

          {/* Submit */}
          <div className="flex gap-3">
            <Button
              type="button"
              variant="secondary"
              onClick={() => router.push('/care')}
              fullWidth
            >
              Cancel
            </Button>
            <Button
              type="submit"
              loading={saving}
              fullWidth
            >
              Add Note
            </Button>
          </div>
        </form>
      </PageContainer>
    </>
  )
}
