"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
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 { Alert, AlertDescription } from "@/components/ui/alert"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import Link from "next/link"

export default function RegisterForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    confirmPassword: "",
    phone: "",
    role: "customer" as "customer" | "plumber",
    address: "",
    specialization: "",
    experience: "",
  })
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const router = useRouter()

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

    if (formData.password !== formData.confirmPassword) {
      setError("كلمات المرور غير متطابقة")
      setLoading(false)
      return
    }

    try {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      })

      const data = await response.json()

      if (response.ok) {
        router.push("/login?message=تم إنشاء الحساب بنجاح")
      } else {
        setError(data.error || "حدث خطأ في إنشاء الحساب")
      }
    } catch (err) {
      setError("حدث خطأ في الاتصال")
    } finally {
      setLoading(false)
    }
  }

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl font-bold text-[var(--dark-color)]">إنشاء حساب جديد</CardTitle>
        <CardDescription className="text-[var(--parg-color)]">املأ البيانات التالية لإنشاء حسابك</CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && (
            <Alert className="border-[var(--dark-red)] bg-red-50">
              <AlertDescription className="text-[var(--dark-red)]">{error}</AlertDescription>
            </Alert>
          )}

          <div className="space-y-2">
            <Label htmlFor="role" className="text-[var(--dark-color)]">
              نوع الحساب
            </Label>
            <Select
              value={formData.role}
              onValueChange={(value: "customer" | "plumber") => setFormData((prev) => ({ ...prev, role: value }))}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="customer">عميل</SelectItem>
                <SelectItem value="plumber">سباك</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="name" className="text-[var(--dark-color)]">
              الاسم الكامل
            </Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
              required
              className="text-right"
              placeholder="أدخل اسمك الكامل"
            />
          </div>

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

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

          {formData.role === "customer" && (
            <div className="space-y-2">
              <Label htmlFor="address" className="text-[var(--dark-color)]">
                العنوان
              </Label>
              <Input
                id="address"
                value={formData.address}
                onChange={(e) => setFormData((prev) => ({ ...prev, address: e.target.value }))}
                className="text-right"
                placeholder="أدخل عنوانك"
              />
            </div>
          )}

          {formData.role === "plumber" && (
            <>
              <div className="space-y-2">
                <Label htmlFor="specialization" className="text-[var(--dark-color)]">
                  التخصص
                </Label>
                <Input
                  id="specialization"
                  value={formData.specialization}
                  onChange={(e) => setFormData((prev) => ({ ...prev, specialization: e.target.value }))}
                  className="text-right"
                  placeholder="مثال: سباكة عامة، تسليك مجاري"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="experience" className="text-[var(--dark-color)]">
                  سنوات الخبرة
                </Label>
                <Input
                  id="experience"
                  type="number"
                  value={formData.experience}
                  onChange={(e) => setFormData((prev) => ({ ...prev, experience: e.target.value }))}
                  className="text-right"
                  placeholder="5"
                />
              </div>
            </>
          )}

          <div className="space-y-2">
            <Label htmlFor="password" className="text-[var(--dark-color)]">
              كلمة المرور
            </Label>
            <Input
              id="password"
              type="password"
              value={formData.password}
              onChange={(e) => setFormData((prev) => ({ ...prev, password: e.target.value }))}
              required
              className="text-right"
              placeholder="••••••••"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirmPassword" className="text-[var(--dark-color)]">
              تأكيد كلمة المرور
            </Label>
            <Input
              id="confirmPassword"
              type="password"
              value={formData.confirmPassword}
              onChange={(e) => setFormData((prev) => ({ ...prev, confirmPassword: e.target.value }))}
              required
              className="text-right"
              placeholder="••••••••"
            />
          </div>

          <Button
            type="submit"
            disabled={loading}
            className="w-full bg-[var(--main-color)] hover:bg-[var(--main-color)]/90 text-[var(--dark-color)] font-medium"
          >
            {loading ? "جاري إنشاء الحساب..." : "إنشاء الحساب"}
          </Button>

          <div className="text-center">
            <p className="text-sm text-[var(--parg-color)]">
              لديك حساب بالفعل؟{" "}
              <Link href="/login" className="text-[var(--name-item)] hover:underline">
                تسجيل الدخول
              </Link>
            </p>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
