"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Upload, User, Briefcase, Building, Phone, MapPin, BadgeIcon as IdCard } from "lucide-react"

interface PersonalInformationSettingsProps {
  user: any
}

export function PersonalInformationSettings({ user }: PersonalInformationSettingsProps) {
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState("")
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    biography: "",
    location: "",
    employeeId: "",
    jobTitle: "",
    department: "",
    supervisorName: "",
    phoneNumber: "",
    employmentType: "",
  })

  // Load user data from database on component mount
  useEffect(() => {
    const loadUserData = async () => {
      try {
        const response = await fetch("/api/user/profile")
        if (response.ok) {
          const data = await response.json()
          if (data.user) {
            setFormData({
              name: data.user.name || "",
              email: data.user.email || "",
              biography: data.user.biography || "",
              location: data.user.location || "",
              employeeId: data.user.employeeId || "",
              jobTitle: data.user.jobTitle || "",
              department: data.user.department || "",
              supervisorName: data.user.supervisorName || "",
              phoneNumber: data.user.phoneNumber || "",
              employmentType: data.user.employmentType || "",
            })
          }
        }
      } catch (error) {
        console.error("Error loading user data:", error)
      }
    }

    loadUserData()
  }, [])

  // Also update when user prop changes (fallback)
  useEffect(() => {
    if (user) {
      setFormData((prev) => ({
        name: user.name || prev.name,
        email: user.email || prev.email,
        biography: user.biography || prev.biography,
        location: user.location || prev.location,
        employeeId: user.employeeId || prev.employeeId,
        jobTitle: user.jobTitle || prev.jobTitle,
        department: user.department || prev.department,
        supervisorName: user.supervisorName || prev.supervisorName,
        phoneNumber: user.phoneNumber || prev.phoneNumber,
        employmentType: user.employmentType || prev.employmentType,
      }))
    }
  }, [user])

  const handleSave = async () => {
    setIsLoading(true)
    setMessage("")

    try {
      const response = await fetch("/api/user/profile", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      })

      const data = await response.json()

      if (response.ok) {
        setMessage("Profile updated successfully!")
        // Update form data with the response
        if (data.user) {
          setFormData({
            name: data.user.name || "",
            email: data.user.email || "",
            biography: data.user.biography || "",
            location: data.user.location || "",
            employeeId: data.user.employeeId || "",
            jobTitle: data.user.jobTitle || "",
            department: data.user.department || "",
            supervisorName: data.user.supervisorName || "",
            phoneNumber: data.user.phoneNumber || "",
            employmentType: data.user.employmentType || "",
          })
        }
        // Clear message after 3 seconds
        setTimeout(() => setMessage(""), 3000)
      } else {
        setMessage(data.error || "Failed to update profile")
      }
    } catch (error) {
      console.error("Save error:", error)
      setMessage("Failed to update profile")
    } finally {
      setIsLoading(false)
    }
  }

  const employmentTypes = ["Full-time", "Part-time", "Contract", "Intern", "Consultant", "Freelancer"]

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Profile Information</CardTitle>
          <CardDescription>Update your personal information and profile details</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Avatar Section */}
          <div className="flex items-center gap-4">
            <Avatar className="h-20 w-20">
              <AvatarImage src={user?.avatar || "/placeholder.svg"} alt={user.name}/>
              <AvatarFallback className="rounded-lg text-2xl">
                {user.name?.charAt(0)?.toUpperCase()|| "U"}
              </AvatarFallback>
            </Avatar>
            <div className="space-y-2">
              <Button variant="outline" size="sm">
                <Upload className="h-4 w-4 mr-2" />
                Upload Photo
              </Button>
              <p className="text-xs text-muted-foreground">JPG, PNG or GIF. Max size 2MB.</p>
            </div>
          </div>

          {/* Message Display */}
          {message && (
            <div
              className={`p-3 rounded-md text-sm ${
                message.includes("successfully")
                  ? "bg-green-50 text-green-700 border border-green-200"
                  : "bg-red-50 text-red-700 border border-red-200"
              }`}
            >
              {message}
            </div>
          )}

          {/* Basic Information */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">Basic Information</h3>
            <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"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="Enter your full name"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">Email Address</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  placeholder="Enter your email"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="phoneNumber">
                  <Phone className="h-4 w-4 inline mr-1" />
                  Phone Number
                </Label>
                <Input
                  id="phoneNumber"
                  type="tel"
                  value={formData.phoneNumber}
                  onChange={(e) => setFormData({ ...formData, phoneNumber: e.target.value })}
                  placeholder="Enter your phone number"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="location">
                  <MapPin className="h-4 w-4 inline mr-1" />
                  Location
                </Label>
                <Input
                  id="location"
                  value={formData.location}
                  onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                  placeholder="City, Country"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="biography">Biography</Label>
              <Textarea
                id="biography"
                value={formData.biography}
                onChange={(e) => setFormData({ ...formData, biography: e.target.value })}
                className="resize-none"
                placeholder="Tell us about yourself..."
                rows={3}
              />
            </div>
          </div>

          {/* Employment Information */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">Employment Information</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="employeeId">
                  <IdCard className="h-4 w-4 inline mr-1" />
                  Employee ID
                </Label>
                <Input
                  id="employeeId"
                  value={formData.employeeId}
                  onChange={(e) => setFormData({ ...formData, employeeId: e.target.value })}
                  placeholder="Enter your employee ID"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="jobTitle">
                  <Briefcase className="h-4 w-4 inline mr-1" />
                  Job Title
                </Label>
                <Input
                  id="jobTitle"
                  value={formData.jobTitle}
                  onChange={(e) => setFormData({ ...formData, jobTitle: e.target.value })}
                  placeholder="Enter your job title"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="department">
                  <Building className="h-4 w-4 inline mr-1" />
                  Department
                </Label>
                <Input
                  id="department"
                  value={formData.department}
                  onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                  placeholder="Enter your department"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="supervisorName">
                  <User className="h-4 w-4 inline mr-1" />
                  Supervisor/Manager Name
                </Label>
                <Input
                  id="supervisorName"
                  value={formData.supervisorName}
                  onChange={(e) => setFormData({ ...formData, supervisorName: e.target.value })}
                  placeholder="Enter your supervisor or manager name"
                />
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="employmentType">Employment Type</Label>
                <Select
                  value={formData.employmentType}
                  onValueChange={(value) => setFormData({ ...formData, employmentType: value })}
                >
                  <SelectTrigger className="cursor-pointer">
                    <SelectValue placeholder="Select employment type" />
                  </SelectTrigger>
                  <SelectContent>
                    {employmentTypes.map((type) => (
                      <SelectItem key={type} value={type} className="cursor-pointer">
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>

          <div className="flex justify-end">
            <Button onClick={handleSave} disabled={isLoading} className="cursor-pointer">
              {isLoading ? "Saving..." : "Save Changes"}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
