'use client'

import { Suspense, use, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
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 { Switch } from '@/components/ui/switch'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  ArrowLeft,
  Loader2,
  Save,
  Plus,
  GripVertical,
  Trash2,
  Settings,
  Eye,
  Mail,
  Link2,
} from 'lucide-react'
import { toast } from 'sonner'
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core'
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { cn } from '@/lib/utils'

interface PageProps {
  params: Promise<{ id: string }>
}

// Sortable step item component
function SortableStep({
  step,
  isSelected,
  onSelect,
  onDelete,
}: {
  step: { id: string; name: string; title: string; fields: unknown[] }
  isSelected: boolean
  onSelect: () => void
  onDelete: () => void
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: step.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={cn(
        'flex items-center gap-2 p-3 rounded-lg border cursor-pointer transition-colors',
        isSelected ? 'border-primary bg-primary/5' : 'border-transparent hover:bg-muted',
        isDragging && 'opacity-50'
      )}
      onClick={onSelect}
    >
      <button
        {...attributes}
        {...listeners}
        className="cursor-grab text-muted-foreground hover:text-foreground"
        onClick={(e) => e.stopPropagation()}
      >
        <GripVertical className="h-4 w-4" />
      </button>
      <div className="flex-1 min-w-0">
        <p className="font-medium truncate">{step.title}</p>
        <p className="text-xs text-muted-foreground">
          {(step.fields as unknown[]).length} fields
        </p>
      </div>
      <button
        className="p-1 text-muted-foreground hover:text-destructive"
        onClick={(e) => {
          e.stopPropagation()
          onDelete()
        }}
      >
        <Trash2 className="h-4 w-4" />
      </button>
    </div>
  )
}

function OnboardingFormEditor({ formId }: { formId: string }) {
  const router = useRouter()
  const utils = trpc.useUtils()

  // Fetch form data with steps
  const { data: form, isLoading } = trpc.applicationForm.getForBuilder.useQuery(
    { id: formId },
    { refetchOnWindowFocus: false }
  )

  // Local state for editing
  const [selectedStepId, setSelectedStepId] = useState<string | null>(null)
  const [isSaving, setIsSaving] = useState(false)

  // Mutations
  const updateForm = trpc.applicationForm.update.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      toast.success('Form updated')
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  const createStep = trpc.applicationForm.createStep.useMutation({
    onSuccess: (data) => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      setSelectedStepId(data.id)
      toast.success('Step created')
    },
  })

  const updateStep = trpc.applicationForm.updateStep.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      toast.success('Step updated')
    },
  })

  const deleteStep = trpc.applicationForm.deleteStep.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      setSelectedStepId(null)
      toast.success('Step deleted')
    },
  })

  const reorderSteps = trpc.applicationForm.reorderSteps.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
    },
  })

  const updateEmailSettings = trpc.applicationForm.updateEmailSettings.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      toast.success('Email settings updated')
    },
  })

  const linkToRound = trpc.applicationForm.linkToRound.useMutation({
    onSuccess: () => {
      utils.applicationForm.getForBuilder.invalidate({ id: formId })
      toast.success('Round linked')
    },
  })

  // Fetch available rounds
  const { data: availableRounds } = trpc.applicationForm.getAvailableRounds.useQuery({
    programId: form?.programId || undefined,
  })

  // DnD sensors
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  )

  const handleStepDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    if (!over || active.id === over.id || !form) return

    const oldIndex = form.steps.findIndex((s) => s.id === active.id)
    const newIndex = form.steps.findIndex((s) => s.id === over.id)

    const newOrder = arrayMove(form.steps, oldIndex, newIndex)
    reorderSteps.mutate({
      formId,
      stepIds: newOrder.map((s) => s.id),
    })
  }

  const handleAddStep = () => {
    const stepNumber = (form?.steps.length || 0) + 1
    createStep.mutate({
      formId,
      step: {
        name: `step_${stepNumber}`,
        title: `Step ${stepNumber}`,
      },
    })
  }

  const selectedStep = form?.steps.find((s) => s.id === selectedStepId)

  if (isLoading) {
    return <FormEditorSkeleton />
  }

  if (!form) {
    return (
      <div className="text-center py-12">
        <p className="text-muted-foreground">Form not found</p>
        <Link href="/admin/onboarding">
          <Button variant="outline" className="mt-4">
            Back to Onboarding
          </Button>
        </Link>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/admin/onboarding">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back
          </Link>
        </Button>
      </div>

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">{form.name}</h1>
          <div className="flex items-center gap-2 mt-1">
            <Badge variant={form.status === 'PUBLISHED' ? 'default' : 'secondary'}>
              {form.status}
            </Badge>
            {form.round && (
              <Badge variant="outline">
                <Link2 className="mr-1 h-3 w-3" />
                {form.round.name}
              </Badge>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          {form.publicSlug && form.status === 'PUBLISHED' && (
            <a href={`/apply/${form.publicSlug}`} target="_blank" rel="noopener noreferrer">
              <Button variant="outline">
                <Eye className="mr-2 h-4 w-4" />
                Preview
              </Button>
            </a>
          )}
        </div>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="steps" className="space-y-6">
        <TabsList>
          <TabsTrigger value="steps">Steps & Fields</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
          <TabsTrigger value="emails">Emails</TabsTrigger>
        </TabsList>

        {/* Steps Tab */}
        <TabsContent value="steps" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Steps List */}
            <Card className="lg:col-span-1">
              <CardHeader className="pb-3">
                <CardTitle className="text-base">Steps</CardTitle>
                <CardDescription>
                  Drag to reorder wizard steps
                </CardDescription>
              </CardHeader>
              <CardContent>
                <DndContext
                  sensors={sensors}
                  collisionDetection={closestCenter}
                  onDragEnd={handleStepDragEnd}
                >
                  <SortableContext
                    items={form.steps.map((s) => s.id)}
                    strategy={verticalListSortingStrategy}
                  >
                    <div className="space-y-1">
                      {form.steps.map((step) => (
                        <SortableStep
                          key={step.id}
                          step={step}
                          isSelected={selectedStepId === step.id}
                          onSelect={() => setSelectedStepId(step.id)}
                          onDelete={() => {
                            if (confirm('Delete this step? Fields will be unassigned.')) {
                              deleteStep.mutate({ id: step.id })
                            }
                          }}
                        />
                      ))}
                    </div>
                  </SortableContext>
                </DndContext>

                <Button
                  variant="outline"
                  size="sm"
                  className="w-full mt-4"
                  onClick={handleAddStep}
                  disabled={createStep.isPending}
                >
                  {createStep.isPending ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <Plus className="mr-2 h-4 w-4" />
                  )}
                  Add Step
                </Button>
              </CardContent>
            </Card>

            {/* Step Editor */}
            <Card className="lg:col-span-2">
              <CardHeader className="pb-3">
                <CardTitle className="text-base">
                  {selectedStep ? `Edit: ${selectedStep.title}` : 'Select a Step'}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {selectedStep ? (
                  <div className="space-y-4">
                    <div className="grid gap-4 sm:grid-cols-2">
                      <div className="space-y-2">
                        <Label>Step Title</Label>
                        <Input
                          value={selectedStep.title}
                          onChange={(e) => {
                            updateStep.mutate({
                              id: selectedStep.id,
                              step: { title: e.target.value },
                            })
                          }}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>Internal Name</Label>
                        <Input
                          value={selectedStep.name}
                          onChange={(e) => {
                            updateStep.mutate({
                              id: selectedStep.id,
                              step: { name: e.target.value },
                            })
                          }}
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label>Description (optional)</Label>
                      <Textarea
                        value={selectedStep.description || ''}
                        onChange={(e) => {
                          updateStep.mutate({
                            id: selectedStep.id,
                            step: { description: e.target.value },
                          })
                        }}
                        rows={3}
                      />
                    </div>

                    <div className="pt-4 border-t">
                      <h4 className="font-medium mb-3">Fields in this step</h4>
                      {selectedStep.fields.length === 0 ? (
                        <p className="text-sm text-muted-foreground">
                          No fields yet. Use the existing form editor to add fields.
                        </p>
                      ) : (
                        <div className="space-y-2">
                          {selectedStep.fields.map((field) => (
                            <div
                              key={field.id}
                              className="flex items-center gap-3 p-3 rounded-lg border bg-muted/50"
                            >
                              <GripVertical className="h-4 w-4 text-muted-foreground" />
                              <div className="flex-1">
                                <p className="font-medium text-sm">{field.label}</p>
                                <p className="text-xs text-muted-foreground">
                                  {field.fieldType} {field.required && '(required)'}
                                </p>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                      <Link href={`/admin/forms/${formId}`}>
                        <Button variant="outline" size="sm" className="mt-4">
                          Edit Fields in Form Editor
                        </Button>
                      </Link>
                    </div>
                  </div>
                ) : (
                  <p className="text-muted-foreground text-center py-8">
                    Select a step from the list to edit it
                  </p>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Settings Tab */}
        <TabsContent value="settings" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">General Settings</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Form Name</Label>
                <Input
                  value={form.name}
                  onChange={(e) => {
                    updateForm.mutate({ id: formId, name: e.target.value })
                  }}
                />
              </div>

              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea
                  value={form.description || ''}
                  onChange={(e) => {
                    updateForm.mutate({ id: formId, description: e.target.value || null })
                  }}
                  rows={3}
                />
              </div>

              <div className="space-y-2">
                <Label>Public URL Slug</Label>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">/apply/</span>
                  <Input
                    value={form.publicSlug || ''}
                    onChange={(e) => {
                      updateForm.mutate({ id: formId, publicSlug: e.target.value || null })
                    }}
                    placeholder="your-form-slug"
                  />
                </div>
              </div>

              <div className="flex items-center justify-between pt-4">
                <div>
                  <Label>Public Access</Label>
                  <p className="text-sm text-muted-foreground">
                    Allow public submissions to this form
                  </p>
                </div>
                <Switch
                  checked={form.isPublic}
                  onCheckedChange={(checked) => {
                    updateForm.mutate({ id: formId, isPublic: checked })
                  }}
                />
              </div>

              <div className="space-y-2 pt-4">
                <Label>Status</Label>
                <Select
                  value={form.status}
                  onValueChange={(value) => {
                    updateForm.mutate({ id: formId, status: value as 'DRAFT' | 'PUBLISHED' | 'CLOSED' })
                  }}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="DRAFT">Draft</SelectItem>
                    <SelectItem value="PUBLISHED">Published</SelectItem>
                    <SelectItem value="CLOSED">Closed</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Round Linking</CardTitle>
              <CardDescription>
                Link this form to a round to create projects on submission
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Linked Round</Label>
                <Select
                  value={form.roundId || 'none'}
                  onValueChange={(value) => {
                    linkToRound.mutate({
                      formId,
                      roundId: value === 'none' ? null : value,
                    })
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select a round" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">No round linked</SelectItem>
                    {form.round && (
                      <SelectItem value={form.round.id}>
                        {form.round.name} (current)
                      </SelectItem>
                    )}
                    {availableRounds?.map((round) => (
                      <SelectItem key={round.id} value={round.id}>
                        {round.program?.name} {round.program?.year} - {round.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Emails Tab */}
        <TabsContent value="emails" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Email Notifications</CardTitle>
              <CardDescription>
                Configure emails sent when applications are submitted
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <Label>Confirmation Email</Label>
                  <p className="text-sm text-muted-foreground">
                    Send a confirmation email to the applicant
                  </p>
                </div>
                <Switch
                  checked={form.sendConfirmationEmail}
                  onCheckedChange={(checked) => {
                    updateEmailSettings.mutate({
                      formId,
                      sendConfirmationEmail: checked,
                    })
                  }}
                />
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <Label>Team Invite Emails</Label>
                  <p className="text-sm text-muted-foreground">
                    Send invite emails to team members
                  </p>
                </div>
                <Switch
                  checked={form.sendTeamInviteEmails}
                  onCheckedChange={(checked) => {
                    updateEmailSettings.mutate({
                      formId,
                      sendTeamInviteEmails: checked,
                    })
                  }}
                />
              </div>

              {form.sendConfirmationEmail && (
                <>
                  <div className="space-y-2 pt-4 border-t">
                    <Label>Custom Email Subject (optional)</Label>
                    <Input
                      value={form.confirmationEmailSubject || ''}
                      onChange={(e) => {
                        updateEmailSettings.mutate({
                          formId,
                          confirmationEmailSubject: e.target.value || null,
                        })
                      }}
                      placeholder="Application Received - {projectName}"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Custom Email Message (optional)</Label>
                    <Textarea
                      value={form.confirmationEmailBody || ''}
                      onChange={(e) => {
                        updateEmailSettings.mutate({
                          formId,
                          confirmationEmailBody: e.target.value || null,
                        })
                      }}
                      placeholder="Add a custom message to include in the confirmation email..."
                      rows={4}
                    />
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

function FormEditorSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-9 w-24" />
      <div className="flex items-center justify-between">
        <div className="space-y-2">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-5 w-32" />
        </div>
      </div>
      <Skeleton className="h-10 w-64" />
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Skeleton className="h-96" />
        <Skeleton className="h-96 lg:col-span-2" />
      </div>
    </div>
  )
}

export default function OnboardingFormPage({ params }: PageProps) {
  const { id } = use(params)

  return (
    <Suspense fallback={<FormEditorSkeleton />}>
      <OnboardingFormEditor formId={id} />
    </Suspense>
  )
}
