"use client"

import { useState, useEffect } from "react"
import { useRouter, useParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ArrowLeft, Save, Upload } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { getStudentById } from "@/services/students/mock"

export default function EditStudentPage() {
  const router = useRouter()
  const params = useParams()
  const { toast } = useToast()
  const studentId = Number.parseInt(params.id as string)

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    contact_number: "",
    avatar: "",
  })
  const [loading, setLoading] = useState(false)
  const [student, setStudent] = useState<any>(null)

  useEffect(() => {
    const studentData = getStudentById(studentId)
    if (studentData) {
      setStudent(studentData)
      setFormData({
        name: studentData.name || "",
        email: studentData.email || "",
        contact_number: studentData.contact_number || "",
        avatar: studentData.avatar || "",
      })
    }
  }, [studentId])

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }))
  }

  const handleSave = async () => {
    setLoading(true)
    try {
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 1000))

      console.log("[student][update]", {
        id: studentId,
        ...formData,
      })

      toast({
        title: "Success",
        description: "Student updated successfully",
      })

      setTimeout(() => {
        router.push("/admin/students")
      }, 1000)
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to update student",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }

  if (!student) {
    return (
      <div className="p-6">
        <div className="text-center">Student not found</div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center gap-2">
        <Button variant="ghost" size="icon" onClick={() => router.push("/admin/students")}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Student</h1>
          <p className="text-gray-600">Update student information</p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Student Information</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Avatar Section */}
          <div className="space-y-2">
            <Label>Profile Picture</Label>
            <div className="flex items-center gap-4">
              <div className="w-20 h-20 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">
                {formData.avatar ? (
                  <img
                    src={formData.avatar || "/placeholder.svg"}
                    alt="Student avatar"
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <span className="text-gray-500 text-sm">No Image</span>
                )}
              </div>
              <div className="space-y-2">
                <Input
                  placeholder="Avatar URL"
                  value={formData.avatar}
                  onChange={(e) => handleInputChange("avatar", e.target.value)}
                />
                <Button variant="outline" size="sm">
                  <Upload className="h-4 w-4 mr-2" />
                  Upload Image
                </Button>
              </div>
            </div>
          </div>

          {/* Basic Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="name">Full Name *</Label>
              <Input
                id="name"
                placeholder="Enter student name"
                value={formData.name}
                onChange={(e) => handleInputChange("name", e.target.value)}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Email Address *</Label>
              <Input
                id="email"
                type="email"
                placeholder="Enter email address"
                value={formData.email}
                onChange={(e) => handleInputChange("email", e.target.value)}
                required
              />
            </div>
          </div>

          {/* Contact Information */}
          <div className="space-y-2">
            <Label htmlFor="contact_number">Contact Number</Label>
            <Input
              id="contact_number"
              placeholder="Enter contact number"
              value={formData.contact_number}
              onChange={(e) => handleInputChange("contact_number", e.target.value)}
            />
          </div>

          {/* Student Details */}
          <div className="bg-gray-50 p-4 rounded-lg space-y-2">
            <h3 className="font-medium text-gray-900">Student Details</h3>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600">Student ID:</span>
                <span className="ml-2 font-medium">#{student.id}</span>
              </div>
              <div>
                <span className="text-gray-600">User ID:</span>
                <span className="ml-2 font-medium">#{student.user_id}</span>
              </div>
              <div>
                <span className="text-gray-600">Created:</span>
                <span className="ml-2 font-medium">{new Date(student.created_at).toLocaleDateString()}</span>
              </div>
              <div>
                <span className="text-gray-600">Last Updated:</span>
                <span className="ml-2 font-medium">{new Date(student.updated_at).toLocaleDateString()}</span>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex gap-2 pt-4">
            <Button onClick={handleSave} disabled={loading || !formData.name || !formData.email}>
              <Save className="h-4 w-4 mr-2" />
              {loading ? "Saving..." : "Save Changes"}
            </Button>
            <Button variant="outline" onClick={() => router.push("/admin/students")}>
              Cancel
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
