"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { ArrowLeft, Save, User, Mail, Phone, FileText, ImageIcon, AlertTriangle } 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 { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { getInstructorById, updateInstructor } 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 EditInstructorPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const { toast } = useToast()
  const instructorId = Number.parseInt(params.id)

  const [instructor, setInstructor] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [formData, setFormData] = useState<InstructorFormData>({
    name: "",
    email: "",
    phone: "",
    summary: "",
    description: "",
    avatar: "",
  })

  // Fetch instructor data
  useEffect(() => {
    const fetchInstructor = async () => {
      try {
        setIsLoading(true)
        setError(null)

        const instructorData = await getInstructorById(instructorId)

        if (instructorData) {
          setInstructor(instructorData)
          setFormData({
            name: instructorData.name || "",
            email: instructorData.email || "",
            phone: instructorData.phone || "",
            summary: instructorData.summary || "",
            description: instructorData.description || "",
            avatar: instructorData.avatar || "",
          })
        } else {
          setError("Instructor not found")
        }
      } catch (err) {
        console.error("Failed to fetch instructor:", err)
        setError("Failed to load instructor data")
      } finally {
        setIsLoading(false)
      }
    }

    fetchInstructor()
  }, [instructorId])

  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 {
      await updateInstructor(instructorId, formData)

      toast({
        title: "Success",
        description: "Instructor updated successfully",
      })

      // Navigate back after a short delay
      setTimeout(() => {
        router.push(`/admin/instructors/${instructorId}`)
      }, 1000)
    } catch (err) {
      console.error("Failed to update instructor:", err)
      toast({
        title: "Error",
        description: "Failed to update instructor. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  if (isLoading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading instructor data...</p>
        </div>
      </div>
    )
  }

  if (error || !instructor) {
    return (
      <div className="p-6">
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>{error || "Instructor not found"}</AlertDescription>
        </Alert>
        <Button className="mt-4" variant="outline" onClick={() => router.push("/admin/instructors")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Instructors
        </Button>
      </div>
    )
  }

  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/${instructorId}`)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Edit Instructor</h1>
            <p className="text-muted-foreground">Update {instructor.name}'s profile information</p>
          </div>
        </div>
        <Button
          onClick={handleSubmit}
          disabled={isSubmitting}
          className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700"
        >
          {isSubmitting ? (
            <>Saving...</>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Save Changes
            </>
          )}
        </Button>
      </div>

      {/* Instructor Info */}
      <Card className="bg-blue-50 border-blue-200">
        <CardContent className="p-4">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center">
              {instructor.avatar ? (
                <img
                  src={instructor.avatar || "/placeholder.svg"}
                  alt={instructor.name}
                  className="w-16 h-16 rounded-full object-cover"
                />
              ) : (
                <User className="h-8 w-8 text-blue-600" />
              )}
            </div>
            <div>
              <h3 className="font-semibold text-blue-900">Instructor ID: {instructor.id}</h3>
              <p className="text-sm text-blue-700">User ID: {instructor.user_id}</p>
              <p className="text-sm text-blue-700">Created: {new Date(instructor.created_at).toLocaleDateString()}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Information */}
        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Update 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>
    </div>
  )
}
