'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ChevronLeft, ClipboardList, Clock, User, AlertCircle } from 'lucide-react'

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

const PRIORITIES = [
  { value: 'LOW', label: 'Low', color: 'bg-blue-100 text-blue-700' },
  { value: 'MEDIUM', label: 'Medium', color: 'bg-yellow-100 text-yellow-700' },
  { value: 'HIGH', label: 'High', color: 'bg-orange-100 text-orange-700' },
  { value: 'URGENT', label: 'Urgent', color: 'bg-red-100 text-red-700' },
]

const CATEGORIES = [
  { value: 'GENERAL', label: 'General', emoji: '📝' },
  { value: 'MEDICATION', label: 'Medication', emoji: '💊' },
  { value: 'APPOINTMENT', label: 'Appointment', emoji: '📅' },
  { value: 'SYMPTOM', label: 'Symptom', emoji: '😷' },
]

export default function NewCareTaskPage() {
  const router = useRouter()
  const { currentWorkspace } = useApp()
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [priority, setPriority] = useState('MEDIUM')
  const [category, setCategory] = useState('GENERAL')
  const [dueDate, setDueDate] = useState('')
  const [saving, setSaving] = useState(false)

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

    setSaving(true)
    try {
      const response = await fetch(`/api/workspaces/${currentWorkspace.id}/care-tasks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: title.trim(),
          description: description.trim() || null,
          priority,
          category,
          dueAt: dueDate ? new Date(dueDate).toISOString() : null,
        }),
      })

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

      showToast('Task created!', 'success')
      router.push('/care')
    } catch {
      showToast('Failed to create task', 'error')
    } finally {
      setSaving(false)
    }
  }

  return (
    <>
      <Header 
        title="New Care Task"
        leftAction={{
          icon: <ChevronLeft className="w-6 h-6" />,
          label: 'Back',
          onClick: () => router.push('/care')
        }}
      />
      <PageContainer className="pt-4">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Title */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              <ClipboardList className="w-4 h-4 inline mr-1" />
              Task Title
            </label>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="e.g., Pick up prescription"
              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"
              required
            />
          </Card>

          {/* Category */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              Category
            </label>
            <div className="grid grid-cols-2 gap-2">
              {CATEGORIES.map((cat) => (
                <button
                  key={cat.value}
                  type="button"
                  onClick={() => setCategory(cat.value)}
                  className={`p-3 rounded-lg border-2 text-left transition-all ${
                    category === cat.value
                      ? 'border-primary-500 bg-primary-50'
                      : 'border-border hover:border-secondary-300'
                  }`}
                >
                  <span className="text-xl mr-2">{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>
            <div className="flex flex-wrap gap-2">
              {PRIORITIES.map((p) => (
                <button
                  key={p.value}
                  type="button"
                  onClick={() => setPriority(p.value)}
                  className={`px-4 py-2 rounded-full font-medium transition-all ${
                    priority === p.value
                      ? p.color + ' ring-2 ring-offset-2 ring-secondary-300'
                      : 'bg-secondary-100 text-secondary-600 hover:bg-secondary-200'
                  }`}
                >
                  {p.label}
                </button>
              ))}
            </div>
          </Card>

          {/* Due Date */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              <Clock className="w-4 h-4 inline mr-1" />
              Due Date (optional)
            </label>
            <input
              type="datetime-local"
              value={dueDate}
              onChange={(e) => setDueDate(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"
            />
          </Card>

          {/* Description */}
          <Card>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              Description (optional)
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Any additional details..."
              rows={3}
              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"
            />
          </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
            >
              Create Task
            </Button>
          </div>
        </form>
      </PageContainer>
    </>
  )
}
