"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ArrowLeft, Save, User, Mail, Phone, FileText, ImageIcon, CheckCircle2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { createInstructor } from "@/services/instructors/query"
import { useToast } from "@/hooks/use-toast"

interface InstructorFormData {
  name: string
  email: string
  phone: string
  summary: string
  description: string
  avatar: string
}

export default function AddInstructorPage() {
  const router = useRouter()
  const { toast } = useToast()
  const [isSubmitting, setIsSubmitting] = useState(false)

  const [formData, setFormData] = useState<InstructorFormData>({
    name: "",
    email: "",
    phone: "",
    summary: "",
    description: "",
    avatar: "",
  })

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!formData.name.trim() || !formData.email.trim()) {
      toast({
        title: "Validation Error",
        description: "Name and email are required fields",
        variant: "destructive",
      })
      return
    }

    setIsSubmitting(true)

    try {
      const newInstructor = await createInstructor(formData)

      toast({
        title: "Success",
        description: "Instructor created successfully",
      })

      // Navigate to the new instructor's detail page after a short delay
      setTimeout(() => {
        router.push(`/admin/instructors/${newInstructor.id}`)
      }, 1000)
    } catch (err) {
      console.error("Failed to create instructor:", err)
      toast({
        title: "Error",
        description: "Failed to create instructor. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const isFormValid = formData.name.trim() && formData.email.trim()

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="icon" onClick={() => router.push("/admin/instructors")}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Add Instructor</h1>
            <p className="text-muted-foreground">Create a new instructor profile</p>
          </div>
        </div>
        <Button
          onClick={handleSubmit}
          disabled={isSubmitting || !isFormValid}
          className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700"
        >
          {isSubmitting ? (
            <>Creating...</>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Create Instructor
            </>
          )}
        </Button>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Information */}
        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Enter the instructor's personal and contact information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">
                  <User className="h-4 w-4 inline mr-1" />
                  Full Name *
                </Label>
                <Input
                  id="name"
                  name="name"
                  placeholder="Enter full name"
                  value={formData.name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">
                  <Mail className="h-4 w-4 inline mr-1" />
                  Email Address *
                </Label>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  placeholder="Enter email address"
                  value={formData.email}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="phone">
                  <Phone className="h-4 w-4 inline mr-1" />
                  Phone Number
                </Label>
                <Input
                  id="phone"
                  name="phone"
                  placeholder="Enter phone number"
                  value={formData.phone}
                  onChange={handleInputChange}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="avatar">
                  <ImageIcon className="h-4 w-4 inline mr-1" />
                  Avatar URL
                </Label>
                <Input
                  id="avatar"
                  name="avatar"
                  placeholder="Enter avatar image URL"
                  value={formData.avatar}
                  onChange={handleInputChange}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="summary">
                <FileText className="h-4 w-4 inline mr-1" />
                Professional Summary
              </Label>
              <Input
                id="summary"
                name="summary"
                placeholder="Brief professional summary"
                value={formData.summary}
                onChange={handleInputChange}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">
                <FileText className="h-4 w-4 inline mr-1" />
                Detailed Biography
              </Label>
              <Textarea
                id="description"
                name="description"
                placeholder="Enter detailed biography and qualifications"
                rows={5}
                value={formData.description}
                onChange={handleInputChange}
              />
            </div>
          </CardContent>
        </Card>

        {/* Avatar Preview */}
        {formData.avatar && (
          <Card>
            <CardHeader>
              <CardTitle>Avatar Preview</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4">
                <img
                  src={formData.avatar || "/placeholder.svg"}
                  alt="Avatar preview"
                  className="w-20 h-20 rounded-full object-cover border-2 border-gray-200"
                  onError={(e) => {
                    e.currentTarget.style.display = "none"
                  }}
                />
                <p className="text-sm text-muted-foreground">This is how the avatar will appear in the system</p>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Form Validation Info */}
        <Card className="bg-amber-50 border-amber-200">
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <CheckCircle2 className={`h-4 w-4 ${isFormValid ? "text-green-600" : "text-amber-600"}`} />
              <p className="text-sm text-amber-800">
                {isFormValid
                  ? "Form is ready to submit"
                  : "Please fill in the required fields (Name and Email) to continue"}
              </p>
            </div>
          </CardContent>
        </Card>
      </form>
    </div>
  )
}
