"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { getCurrentUser, type User } from "@/lib/auth"
import { Card, CardContent, 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 { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { UserIcon, Mail, Phone, MapPin, Camera } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"

export default function ProfilePage() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState("")
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    address: "",
  })

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const currentUser = await getCurrentUser()
        if (currentUser) {
          setUser(currentUser)
          setFormData({
            name: currentUser.name || "",
            email: currentUser.email || "",
            phone: currentUser.phone || "",
            address: currentUser.address || "",
          })
        }
      } catch (error) {
        console.error("Error fetching user:", error)
      } finally {
        setLoading(false)
      }
    }

    fetchUser()
  }, [])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    setMessage("")

    try {
      // هنا سيتم إرسال البيانات للخادم
      console.log("Updating profile:", formData)

      // محاكاة API call
      await new Promise((resolve) => setTimeout(resolve, 1000))

      setMessage("تم تحديث الملف الشخصي بنجاح")
    } catch (error) {
      setMessage("حدث خطأ في تحديث البيانات")
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[var(--parg-color)]">جاري التحميل...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-[var(--dark-color)]">الملف الشخصي</h1>
        <p className="text-[var(--parg-color)]">إدارة معلوماتك الشخصية</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Profile Picture */}
        <Card className="border-[var(--border-color)]">
          <CardHeader>
            <CardTitle className="text-[var(--dark-color)]">الصورة الشخصية</CardTitle>
          </CardHeader>
          <CardContent className="text-center space-y-4">
            <Avatar className="w-32 h-32 mx-auto">
              <AvatarImage src={user?.profileImage || "/placeholder.svg"} />
              <AvatarFallback className="text-2xl bg-[var(--main-color)]/10 text-[var(--main-color)]">
                {user?.name?.charAt(0) || "ع"}
              </AvatarFallback>
            </Avatar>

            <div>
              <h3 className="font-semibold text-[var(--dark-color)] mb-1">{user?.name}</h3>
              <p className="text-sm text-[var(--parg-color)]">{user?.email}</p>
            </div>

            <Button variant="outline" className="w-full bg-transparent">
              <Camera className="w-4 h-4 ml-2" />
              تغيير الصورة
            </Button>
          </CardContent>
        </Card>

        {/* Profile Form */}
        <div className="lg:col-span-2">
          <Card className="border-[var(--border-color)]">
            <CardHeader>
              <CardTitle className="text-[var(--dark-color)]">المعلومات الشخصية</CardTitle>
            </CardHeader>
            <CardContent>
              {message && (
                <Alert
                  className={`mb-4 ${message.includes("نجاح") ? "border-green-500 bg-green-50" : "border-red-500 bg-red-50"}`}
                >
                  <AlertDescription className={message.includes("نجاح") ? "text-green-800" : "text-red-800"}>
                    {message}
                  </AlertDescription>
                </Alert>
              )}

              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="name" className="text-[var(--dark-color)]">
                      <UserIcon className="w-4 h-4 inline ml-2" />
                      الاسم الكامل
                    </Label>
                    <Input
                      id="name"
                      value={formData.name}
                      onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                      className="text-right"
                      placeholder="أدخل اسمك الكامل"
                    />
                  </div>

                  <div>
                    <Label htmlFor="email" className="text-[var(--dark-color)]">
                      <Mail className="w-4 h-4 inline ml-2" />
                      البريد الإلكتروني
                    </Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => setFormData((prev) => ({ ...prev, email: e.target.value }))}
                      className="text-right"
                      placeholder="example@email.com"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="phone" className="text-[var(--dark-color)]">
                    <Phone className="w-4 h-4 inline ml-2" />
                    رقم الهاتف
                  </Label>
                  <Input
                    id="phone"
                    value={formData.phone}
                    onChange={(e) => setFormData((prev) => ({ ...prev, phone: e.target.value }))}
                    className="text-right"
                    placeholder="01234567890"
                  />
                </div>

                <div>
                  <Label htmlFor="address" className="text-[var(--dark-color)]">
                    <MapPin className="w-4 h-4 inline ml-2" />
                    العنوان
                  </Label>
                  <Textarea
                    id="address"
                    value={formData.address}
                    onChange={(e) => setFormData((prev) => ({ ...prev, address: e.target.value }))}
                    className="text-right"
                    placeholder="أدخل عنوانك التفصيلي"
                    rows={3}
                  />
                </div>

                <div className="flex gap-4">
                  <Button
                    type="submit"
                    disabled={saving}
                    className="bg-[var(--main-color)] hover:bg-[var(--main-color)]/90 text-[var(--dark-color)]"
                  >
                    {saving ? "جاري الحفظ..." : "حفظ التغييرات"}
                  </Button>

                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setFormData({
                        name: user?.name || "",
                        email: user?.email || "",
                        phone: user?.phone || "",
                        address: user?.address || "",
                      })
                      setMessage("")
                    }}
                  >
                    إلغاء
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
