"use client"

import type React from "react"

import { useEffect, useState, useRef } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"
import { Loader2, Upload } from "lucide-react"

export function ManageProfileContent() {
  const [session, setSession] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [profileImage, setProfileImage] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const toast = useToastEnhanced()

  useEffect(() => {
    const customerSession = sessionStorage.getItem("customer_session")
    if (customerSession) {
      try {
        const sessionData = JSON.parse(customerSession)
        setSession(sessionData)
      } catch (error) {
        console.error("Error parsing session:", error)
      }
    }
  }, [])

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsLoading(true)

    // Simulate API call
    setTimeout(() => {
      toast.success({
        title: "Profile updated",
        description: "Your profile has been successfully updated.",
      })
      setIsLoading(false)
    }, 1000)
  }

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        toast.error({
          title: "File too large",
          description: "Please select an image under 5MB",
        })
        return
      }

      const reader = new FileReader()
      reader.onloadend = () => {
        setProfileImage(reader.result as string)
        toast.success({
          title: "Photo uploaded",
          description: "Your profile photo has been updated",
        })
      }
      reader.readAsDataURL(file)
    }
  }

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2)
  }

  if (!session) {
    return null
  }

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-balance">Manage Profile</h1>
        <p className="text-muted-foreground mt-1">Update your personal information</p>
      </header>

      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Profile Photo</CardTitle>
          <CardDescription>Upload your profile picture</CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <div className="flex items-center gap-4">
            <Avatar className="h-24 w-24 border-2 border-primary/20">
              {profileImage ? (
                <AvatarImage src={profileImage || "/placeholder.svg"} alt="Profile" />
              ) : (
                <AvatarFallback className="bg-primary/10 text-primary font-semibold text-2xl">
                  {getInitials(session.name)}
                </AvatarFallback>
              )}
            </Avatar>
            <div className="flex flex-col gap-2">
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleImageChange}
                className="hidden"
                aria-label="Upload profile photo"
              />
              <Button type="button" variant="outline" onClick={() => fileInputRef.current?.click()} className="gap-2">
                <Upload className="h-4 w-4" />
                Upload Photo
              </Button>
              <p className="text-xs text-muted-foreground">JPG, PNG or GIF. Max 5MB</p>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Personal Information</CardTitle>
          <CardDescription>Update your profile details here</CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">Full Name</Label>
              <Input id="name" type="text" defaultValue={session.name} disabled={isLoading} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" type="email" defaultValue={session.email} disabled={isLoading} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="phone">Phone Number</Label>
              <Input id="phone" type="tel" placeholder="+91 9876543210" disabled={isLoading} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="address">Address</Label>
              <Input id="address" type="text" placeholder="Enter your address" disabled={isLoading} />
            </div>

            <Button type="submit" disabled={isLoading} className="w-full md:w-auto">
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isLoading ? "Saving..." : "Save Changes"}
            </Button>
          </form>
        </CardContent>
      </Card>

      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Change Password</CardTitle>
          <CardDescription>Update your password to keep your account secure</CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <form className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="current-password">Current Password</Label>
              <Input id="current-password" type="password" />
            </div>

            <div className="space-y-2">
              <Label htmlFor="new-password">New Password</Label>
              <Input id="new-password" type="password" />
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirm-password">Confirm New Password</Label>
              <Input id="confirm-password" type="password" />
            </div>

            <Button type="submit" variant="outline" className="w-full md:w-auto bg-transparent">
              Update Password
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
