import { useState } from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  instructorDetailOptions, instructorMutations, instructorKeys,
  instructorBlockedDatesOptions,
  scheduleSlotListOptions, scheduleSlotMutations, scheduleSlotKeys,
  lessonTypeListOptions,
} from '@/api/lessons'
import { InstructorForm } from '@/components/lessons/instructor-form'
import { ScheduleSlotForm } from '@/components/lessons/schedule-slot-form'
import { BlockedDateForm } from '@/components/lessons/blocked-date-form'
import { WeeklySlotGrid } from '@/components/lessons/weekly-slot-grid'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { ArrowLeft, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { ScheduleSlot } from '@/types/lesson'

export const Route = createFileRoute('/_authenticated/lessons/schedule/instructors/$instructorId')({
  validateSearch: (search: Record<string, unknown>) => ({
    tab: (search.tab as string) || 'overview',
  }),
  component: InstructorDetailPage,
})

const TABS = [
  { key: 'overview', label: 'Overview' },
  { key: 'slots', label: 'Schedule Slots' },
  { key: 'blocked', label: 'Blocked Dates' },
]

function InstructorDetailPage() {
  const { instructorId } = Route.useParams()
  const search = Route.useSearch()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const hasPermission = useAuthStore((s) => s.hasPermission)
  const canAdmin = hasPermission('lessons.admin')
  const tab = search.tab

  function setTab(t: string) {
    navigate({ to: '/lessons/schedule/instructors/$instructorId', params: { instructorId }, search: { tab: t } })
  }

  const { data: instructor, isLoading } = useQuery(instructorDetailOptions(instructorId))

  const updateMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => instructorMutations.update(instructorId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: instructorKeys.detail(instructorId) })
      toast.success('Instructor updated')
    },
    onError: (err) => toast.error(err.message),
  })

  if (isLoading) return <div className="text-sm text-muted-foreground">Loading...</div>
  if (!instructor) return <div className="text-sm text-destructive">Instructor not found.</div>

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/schedule', search: { tab: 'instructors', page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
          <ArrowLeft className="h-4 w-4 mr-1" />Back
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold">{instructor.displayName}</h1>
          {instructor.instruments && instructor.instruments.length > 0 && (
            <p className="text-sm text-muted-foreground">{instructor.instruments.join(', ')}</p>
          )}
        </div>
        <Badge variant={instructor.isActive ? 'default' : 'secondary'}>
          {instructor.isActive ? 'Active' : 'Inactive'}
        </Badge>
      </div>

      <div className="flex gap-1 border-b">
        {TABS.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
              tab === t.key
                ? 'border-primary text-primary'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'overview' && (
        <div className="max-w-lg">
          <InstructorForm
            defaultValues={instructor}
            onSubmit={updateMutation.mutate}
            loading={updateMutation.isPending}
          />
        </div>
      )}
      {tab === 'slots' && <ScheduleSlotsTab instructorId={instructorId} canAdmin={canAdmin} />}
      {tab === 'blocked' && <BlockedDatesTab instructorId={instructorId} canAdmin={canAdmin} />}
    </div>
  )
}

// ─── Schedule Slots Tab ───────────────────────────────────────────────────────

function ScheduleSlotsTab({ instructorId, canAdmin }: { instructorId: string; canAdmin: boolean }) {
  const queryClient = useQueryClient()
  const [addOpen, setAddOpen] = useState(false)
  const [editSlot, setEditSlot] = useState<ScheduleSlot | null>(null)

  const { data: slotsData } = useQuery(scheduleSlotListOptions({ page: 1, limit: 100, order: 'asc' }, { instructorId }))
  const { data: lessonTypesData } = useQuery(lessonTypeListOptions({ page: 1, limit: 100, order: 'asc' }))

  const slots = slotsData?.data ?? []
  const lessonTypes = lessonTypesData?.data ?? []

  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => scheduleSlotMutations.create({ ...data, instructorId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: scheduleSlotKeys.all })
      toast.success('Schedule slot added')
      setAddOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) => scheduleSlotMutations.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: scheduleSlotKeys.all })
      toast.success('Slot updated')
      setEditSlot(null)
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: scheduleSlotMutations.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: scheduleSlotKeys.all })
      toast.success('Slot removed')
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <div className="space-y-4">
      {canAdmin && (
        <div className="flex justify-end">
          <Dialog open={addOpen} onOpenChange={setAddOpen}>
            <DialogTrigger asChild>
              <Button><Plus className="mr-2 h-4 w-4" />Add Slot</Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>Add Schedule Slot</DialogTitle></DialogHeader>
              <ScheduleSlotForm
                lessonTypes={lessonTypes}
                onSubmit={createMutation.mutate}
                loading={createMutation.isPending}
              />
            </DialogContent>
          </Dialog>
        </div>
      )}

      {editSlot && (
        <Dialog open={!!editSlot} onOpenChange={(o) => { if (!o) setEditSlot(null) }}>
          <DialogContent>
            <DialogHeader><DialogTitle>Edit Schedule Slot</DialogTitle></DialogHeader>
            <ScheduleSlotForm
              lessonTypes={lessonTypes}
              defaultValues={editSlot}
              onSubmit={(data) => updateMutation.mutate({ id: editSlot.id, data })}
              loading={updateMutation.isPending}
            />
          </DialogContent>
        </Dialog>
      )}

      <WeeklySlotGrid
        slots={slots}
        lessonTypes={lessonTypes}
        onEdit={setEditSlot}
        onDelete={(slot) => deleteMutation.mutate(slot.id)}
      />
    </div>
  )
}

// ─── Blocked Dates Tab ────────────────────────────────────────────────────────

function BlockedDatesTab({ instructorId, canAdmin }: { instructorId: string; canAdmin: boolean }) {
  const queryClient = useQueryClient()
  const [addOpen, setAddOpen] = useState(false)

  const { data: blockedDates, isLoading } = useQuery(instructorBlockedDatesOptions(instructorId))

  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      instructorMutations.addBlockedDate(instructorId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: instructorKeys.blockedDates(instructorId) })
      toast.success('Blocked date added')
      setAddOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => instructorMutations.deleteBlockedDate(instructorId, id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: instructorKeys.blockedDates(instructorId) })
      toast.success('Blocked date removed')
    },
    onError: (err) => toast.error(err.message),
  })

  const dates = blockedDates ?? []

  return (
    <div className="space-y-4">
      {canAdmin && (
        <div className="flex justify-end">
          <Dialog open={addOpen} onOpenChange={setAddOpen}>
            <DialogTrigger asChild>
              <Button><Plus className="mr-2 h-4 w-4" />Add Blocked Date</Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>Add Blocked Date</DialogTitle></DialogHeader>
              <BlockedDateForm onSubmit={createMutation.mutate} loading={createMutation.isPending} />
            </DialogContent>
          </Dialog>
        </div>
      )}

      {isLoading ? (
        <div className="text-sm text-muted-foreground">Loading...</div>
      ) : dates.length === 0 ? (
        <div className="text-sm text-muted-foreground text-center py-8 border rounded-md">
          No blocked dates configured.
        </div>
      ) : (
        <div className="divide-y border rounded-md">
          {dates.map((d) => (
            <div key={d.id} className="flex items-center justify-between px-4 py-3">
              <div>
                <div className="font-medium text-sm">
                  {new Date(d.startDate + 'T00:00:00').toLocaleDateString()} –{' '}
                  {new Date(d.endDate + 'T00:00:00').toLocaleDateString()}
                </div>
                {d.reason && <div className="text-xs text-muted-foreground">{d.reason}</div>}
              </div>
              {canAdmin && (
                <Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(d.id)}>
                  <Trash2 className="h-4 w-4 text-destructive" />
                </Button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
