"use client"
import { useState, useEffect } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2, ArrowRight } from "lucide-react"
import { createPropertyRequest } from "@/services/userPanelService"
import { getCities, getCategories, City, Category } from "@/lib/api"
import { useAuth } from "@/context/AuthContext"

const CreateRequestPage = () => {
    const { token } = useAuth();
    const router = useRouter();
    const [isLoading, setIsLoading] = useState(false);
    const [cities, setCities] = useState<City[]>([]);
    const [categories, setCategories] = useState<Category[]>([]);
    const [isDataLoading, setIsDataLoading] = useState(true);

    const [formData, setFormData] = useState({
        section: "sale",
        category_id: "",
        price: "",
        to_price: "",
        space: "",
        to_space: "",
        description: "",
        city_id: ""
    });

    useEffect(() => {
        const loadInitialData = async () => {
            try {
                const [citiesRes, categoriesRes] = await Promise.all([
                    getCities(),
                    getCategories()
                ]);
                setCities(citiesRes);
                setCategories(categoriesRes);
            } catch (err) {
                console.error("Error loading form data:", err);
            } finally {
                setIsDataLoading(false);
            }
        };
        loadInitialData();
    }, []);

    const handleChange = (name: string, value: string) => {
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!token) {
            alert("يرجى تسجيل الدخول أولاً");
            return;
        }
        try {
            setIsLoading(true);
            const response = await createPropertyRequest(token, formData);
            if (response.success || response.message) {
                alert("تم إضافة الطلب بنجاح");
                router.push('/user-panel/requests');
            }
        } catch (err) {
            console.error("Error creating request:", err);
            alert("فشل في إضافة الطلب، يرجى التأكد من تعبئة جميع البيانات المطلوبة");
        } finally {
            setIsLoading(false);
        }
    };

    if (isDataLoading) {
        return (
            <div className="flex-1 flex items-center justify-center min-h-[400px]">
                <Loader2 className="animate-spin text-primary" size={40} />
            </div>
        );
    }

    return (
        <div className="max-w-2xl mx-auto py-8">
            <div className="flex items-center gap-4 mb-8">
                <Button variant="ghost" size="icon" onClick={() => router.back()} className="rounded-full">
                    <ArrowRight className="rotate-0" />
                </Button>
                <h1 className="text-2xl font-bold text-[#1D293D]">إضافة طلب عقاري جديد</h1>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6 bg-white p-8 rounded-2xl border border-slate-100 shadow-sm">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Section */}
                    <div className="space-y-2">
                        <Label htmlFor="section">نوع المعاملة</Label>
                        <Select value={formData.section} onValueChange={(val) => handleChange("section", val)}>
                            <SelectTrigger>
                                <SelectValue placeholder="اختر النوع" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="sale">شراء</SelectItem>
                                <SelectItem value="rent">استئجار</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>

                    {/* Category */}
                    <div className="space-y-2">
                        <Label htmlFor="category_id">نوع العقار</Label>
                        <Select value={formData.category_id} onValueChange={(val) => handleChange("category_id", val)}>
                            <SelectTrigger>
                                <SelectValue placeholder="اختر نوع العقار" />
                            </SelectTrigger>
                            <SelectContent>
                                {categories.map(cat => (
                                    <SelectItem key={cat.id} value={cat.id.toString()}>{cat.title}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>

                    {/* Price Range */}
                    <div className="space-y-2">
                        <Label htmlFor="price">السعر من</Label>
                        <Input
                            id="price"
                            type="number"
                            placeholder="ريال سعودي"
                            value={formData.price}
                            onChange={(e) => handleChange("price", e.target.value)}
                            required
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="to_price">السعر إلى</Label>
                        <Input
                            id="to_price"
                            type="number"
                            placeholder="ريال سعودي"
                            value={formData.to_price}
                            onChange={(e) => handleChange("to_price", e.target.value)}
                            required
                        />
                    </div>

                    {/* Space Range */}
                    <div className="space-y-2">
                        <Label htmlFor="space">المساحة من (م²)</Label>
                        <Input
                            id="space"
                            type="number"
                            placeholder="م²"
                            value={formData.space}
                            onChange={(e) => handleChange("space", e.target.value)}
                            required
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="to_space">المساحة إلى (م²)</Label>
                        <Input
                            id="to_space"
                            type="number"
                            placeholder="م²"
                            value={formData.to_space}
                            onChange={(e) => handleChange("to_space", e.target.value)}
                            required
                        />
                    </div>

                    {/* City */}
                    <div className="space-y-2">
                        <Label htmlFor="city_id">المدينة</Label>
                        <Select value={formData.city_id} onValueChange={(val) => handleChange("city_id", val)}>
                            <SelectTrigger>
                                <SelectValue placeholder="اختر مدينة" />
                            </SelectTrigger>
                            <SelectContent>
                                {cities.map(city => (
                                    <SelectItem key={city.id} value={city.id.toString()}>{city.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                {/* Description */}
                <div className="space-y-2">
                    <Label htmlFor="description">وصف الطلب</Label>
                    <textarea
                        id="description"
                        className="w-full min-h-[120px] p-4 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
                        placeholder="اكتب هنا تفاصيل العقار الذي تبحث عنه..."
                        value={formData.description}
                        onChange={(e) => handleChange("description", e.target.value)}
                        required
                    />
                </div>

                <div className="pt-4 flex gap-4">
                    <Button type="submit" className="flex-1 rounded-full h-12" disabled={isLoading}>
                        {isLoading ? <Loader2 className="animate-spin w-5 h-5" /> : "إرسال الطلب"}
                    </Button>
                    <Button type="button" variant="outline" className="flex-1 rounded-full h-12" onClick={() => router.back()}>
                        إلغاء
                    </Button>
                </div>
            </form>
        </div>
    );
};

export default CreateRequestPage;
