"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 Link from "next/link"

export default function LoginForm() {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const router = useRouter()

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

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

      const data = await response.json()

      if (response.ok) {
        // توجيه المستخدم حسب دوره
        switch (data.user.role) {
          case "admin":
            router.push("/admin")
            break
          case "plumber":
            router.push("/plumber")
            break
          default:
            router.push("/dashboard")
        }
      } 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="email" className="text-[var(--dark-color)]">
              البريد الإلكتروني
            </Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="text-right"
              placeholder="example@email.com"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="password" className="text-[var(--dark-color)]">
              كلمة المرور
            </Label>
            <Input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(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 space-y-2">
            <p className="text-sm text-[var(--parg-color)]">
              ليس لديك حساب؟{" "}
              <Link href="/register" className="text-[var(--name-item)] hover:underline">
                إنشاء حساب جديد
              </Link>
            </p>
            <p className="text-xs text-[var(--p-color)]">كلمة المرور التجريبية: 123456</p>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
