'use client'

import { useState } from 'react'
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Loader2, Plus, Trash2, GripVertical, Save } from 'lucide-react'
import { toast } from 'sonner'

interface FormEditorProps {
  form: {
    id: string
    name: string
    description: string | null
    status: string
    isPublic: boolean
    publicSlug: string | null
    submissionLimit: number | null
    opensAt: Date | null
    closesAt: Date | null
    confirmationMessage: string | null
    fields: Array<{
      id: string
      fieldType: string
      name: string
      label: string
      description: string | null
      placeholder: string | null
      required: boolean
      sortOrder: number
    }>
  }
}

export function FormEditor({ form }: FormEditorProps) {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState({
    name: form.name,
    description: form.description || '',
    status: form.status,
    isPublic: form.isPublic,
    publicSlug: form.publicSlug || '',
    confirmationMessage: form.confirmationMessage || '',
  })

  const updateForm = trpc.applicationForm.update.useMutation({
    onSuccess: () => {
      toast.success('Form updated successfully')
      router.refresh()
      setIsSubmitting(false)
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to update form')
      setIsSubmitting(false)
    },
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    updateForm.mutate({
      id: form.id,
      name: formData.name,
      status: formData.status as 'DRAFT' | 'PUBLISHED' | 'CLOSED',
      isPublic: formData.isPublic,
      description: formData.description || null,
      publicSlug: formData.publicSlug || null,
      confirmationMessage: formData.confirmationMessage || null,
    })
  }

  return (
    <Tabs defaultValue="settings" className="space-y-6">
      <TabsList>
        <TabsTrigger value="settings">Settings</TabsTrigger>
        <TabsTrigger value="fields">Fields ({form.fields.length})</TabsTrigger>
      </TabsList>

      <TabsContent value="settings">
        <Card>
          <CardHeader>
            <CardTitle>Form Settings</CardTitle>
            <CardDescription>
              Configure the basic settings for this form
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="name">Form Name</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="status">Status</Label>
                  <Select
                    value={formData.status}
                    onValueChange={(value) => setFormData({ ...formData, status: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="DRAFT">Draft</SelectItem>
                      <SelectItem value="PUBLISHED">Published</SelectItem>
                      <SelectItem value="CLOSED">Closed</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  rows={3}
                  maxLength={2000}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="publicSlug">Public URL Slug</Label>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">/apply/</span>
                  <Input
                    id="publicSlug"
                    value={formData.publicSlug}
                    onChange={(e) => setFormData({ ...formData, publicSlug: e.target.value })}
                    className="flex-1"
                  />
                </div>
              </div>

              <div className="flex items-center gap-2">
                <Switch
                  id="isPublic"
                  checked={formData.isPublic}
                  onCheckedChange={(checked) => setFormData({ ...formData, isPublic: checked })}
                />
                <Label htmlFor="isPublic">Public form (accessible without login)</Label>
              </div>

              <div className="space-y-2">
                <Label htmlFor="confirmationMessage">Confirmation Message</Label>
                <Textarea
                  id="confirmationMessage"
                  value={formData.confirmationMessage}
                  onChange={(e) => setFormData({ ...formData, confirmationMessage: e.target.value })}
                  placeholder="Thank you for your submission..."
                  rows={3}
                  maxLength={1000}
                />
              </div>

              <div className="flex justify-end pt-4">
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Save className="mr-2 h-4 w-4" />
                  Save Settings
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </TabsContent>

      <TabsContent value="fields">
        <Card>
          <CardHeader>
            <CardTitle>Form Fields</CardTitle>
            <CardDescription>
              Add and arrange the fields for your application form
            </CardDescription>
          </CardHeader>
          <CardContent>
            {form.fields.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <p>No fields added yet.</p>
                <p className="text-sm">Add fields to start building your form.</p>
              </div>
            ) : (
              <div className="space-y-2">
                {form.fields.map((field) => (
                  <div
                    key={field.id}
                    className="flex items-center gap-3 p-3 border rounded-lg"
                  >
                    <GripVertical className="h-4 w-4 text-muted-foreground cursor-grab" />
                    <div className="flex-1">
                      <div className="font-medium">{field.label}</div>
                      <div className="text-sm text-muted-foreground">
                        {field.fieldType} {field.required && '(required)'}
                      </div>
                    </div>
                    <Button variant="ghost" size="icon" aria-label="Delete field">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
            <div className="mt-4">
              <Button variant="outline">
                <Plus className="mr-2 h-4 w-4" />
                Add Field
              </Button>
            </div>
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
  )
}
