import { useState } from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useMutation } from '@tanstack/react-query'
import { lessonPlanTemplateMutations } from '@/api/lessons'
import { TemplateSectionBuilder, type TemplateSectionRow } from '@/components/lessons/template-section-builder'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft } from 'lucide-react'
import { toast } from 'sonner'

export const Route = createFileRoute('/_authenticated/lessons/templates/new')({
  component: NewTemplatePage,
})

function NewTemplatePage() {
  const navigate = useNavigate()

  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [instrument, setInstrument] = useState('')
  const [skillLevel, setSkillLevel] = useState('all_levels')
  const [sections, setSections] = useState<TemplateSectionRow[]>([])

  const mutation = useMutation({
    mutationFn: () =>
      lessonPlanTemplateMutations.create({
        name,
        description: description || undefined,
        instrument: instrument || undefined,
        skillLevel,
        sections: sections.map((s, sIdx) => ({
          title: s.title,
          description: s.description || undefined,
          sortOrder: sIdx,
          items: s.items.map((item, iIdx) => ({
            title: item.title,
            description: item.description || undefined,
            sortOrder: iIdx,
          })),
        })),
      }),
    onSuccess: (template) => {
      toast.success('Template created')
      navigate({ to: '/lessons/templates/$templateId', params: { templateId: template.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
    },
    onError: (err) => toast.error(err.message),
  })

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim()) return
    mutation.mutate()
  }

  const allSectionsValid = sections.every(
    (s) => s.title.trim() && s.items.every((i) => i.title.trim()),
  )

  return (
    <form onSubmit={handleSubmit} className="space-y-6 max-w-3xl">
      <div className="flex items-center gap-3">
        <Button type="button" variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/templates', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <h1 className="text-2xl font-bold">New Template</h1>
      </div>

      <Card>
        <CardHeader><CardTitle className="text-lg">Details</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Name *</Label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Piano Foundations — Beginner" required />
          </div>
          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder="What this curriculum covers..." />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Instrument</Label>
              <Input value={instrument} onChange={(e) => setInstrument(e.target.value)} placeholder="e.g. Piano, Guitar" />
            </div>
            <div className="space-y-2">
              <Label>Skill Level</Label>
              <Select value={skillLevel} onValueChange={setSkillLevel}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="beginner">Beginner</SelectItem>
                  <SelectItem value="intermediate">Intermediate</SelectItem>
                  <SelectItem value="advanced">Advanced</SelectItem>
                  <SelectItem value="all_levels">All Levels</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle className="text-lg">Curriculum</CardTitle></CardHeader>
        <CardContent>
          <TemplateSectionBuilder sections={sections} onChange={setSections} />
        </CardContent>
      </Card>

      <div className="flex gap-2">
        <Button type="submit" disabled={mutation.isPending || !name.trim() || !allSectionsValid} size="lg">
          {mutation.isPending ? 'Creating...' : 'Create Template'}
        </Button>
        <Button type="button" variant="secondary" size="lg" onClick={() => navigate({ to: '/lessons/templates', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
          Cancel
        </Button>
      </div>
    </form>
  )
}
