'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Plus, Target, ChevronLeft } from 'lucide-react'

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

export default function TreatmentPage() {
  const router = useRouter()
  const { currentWorkspace } = useApp()
  const [plan, setPlan] = useState(null)
  const [loading, setLoading] = useState(true)

  const fetchPlan = async () => {
    try {
      const response = await fetch(`/api/workspaces/${currentWorkspace.id}/treatment-plan`)
      if (response.ok) {
        const data = await response.json()
        setPlan(data.plan)
      }
    } catch (err) {
      console.error('Failed to fetch plan:', err)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchPlan()
  }, [currentWorkspace.id])

  if (loading) {
    return (
      <>
        <Header title="Treatment Plan" />
        <PageContainer>
          <LoadingState message="Loading treatment plan..." />
        </PageContainer>
      </>
    )
  }

  return (
    <>
      <Header 
        title="Treatment Plan"
        leftAction={{
          icon: <ChevronLeft className="w-6 h-6" />,
          label: 'Back',
          onClick: () => router.push('/today')
        }}
      />
      <PageContainer className="pt-4 space-y-6">
        {!plan ? (
          <Card variant="outline" className="text-center py-12">
            <div className="w-16 h-16 rounded-full bg-primary-100 flex items-center justify-center mx-auto mb-4">
              <Target className="w-8 h-8 text-primary-600" />
            </div>
            <h2 className="text-lg font-semibold text-secondary-900 mb-2">
              No Treatment Plan Yet
            </h2>
            <p className="text-secondary-500 mb-6 max-w-xs mx-auto">
              Create a treatment plan to track your progress through chemotherapy and celebrate milestones.
            </p>
            {currentWorkspace.role !== 'VIEWER' && (
              <Button href="/treatment/new">
                <Plus className="w-4 h-4 mr-2" />
                Create Treatment Plan
              </Button>
            )}
          </Card>
        ) : (
          <TreatmentProgress 
            plan={plan} 
            workspaceId={currentWorkspace.id}
            onUpdate={fetchPlan}
          />
        )}
      </PageContainer>
    </>
  )
}
