"use client";

import {
  Box,
  Text,
  Button,
  Group,
  Paper,
  Flex,
  Stepper,
  TextInput,
  Select,
  Stack,
  FileInput,
  Chip,
  Checkbox,
  Switch,
} from "@mantine/core";
import { useState, useEffect } from "react";
import {
  IconUpload,
  IconMapPin,
  IconChevronDown,
  IconList,
  IconVideo,
  IconHome,
  IconCurrencyDollar,
  IconLogin,
  IconCheck,
} from "@tabler/icons-react";
import theme from "@/styles/theme";
import { ReactNode } from "react";
import Image from "next/image";
import styles from "../styles.module.css";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import { notifications } from "@mantine/notifications";

// Types
interface InputField {
  label: string;
  placeholder: string;
  rightSection?: ReactNode;
}

interface SelectField extends InputField {
  data: string[];
}

interface FieldGroup {
  type: "input" | "select";
  fields: (InputField | SelectField)[];
}

interface UploadedFile {
  file: File;
  preview: string;
  size: string;
  id: number;
}

interface PropertyFormData {
  type: string;
  house_code: string;
  house_name: string;
  house_short_name: string;
  house_space: string;
  city_id: string;
  area: string;
  neighborhood: string;
  longitude: string;
  latitude: string;
  basic_login_time: string;
  basic_logout_time: string;
  number_of_halls: string;
  number_of_rooms: string;
  number_of_bathrooms: string;
  number_of_chairs: string;
  number_of_kitchens: string;
  dining_session: string;
  maximum_guests: string;
  maximum_number_of_nights: string;
  [key: string]: string;
}

// Reusable input styles
const inputStyles = {
  input: {
    borderRadius: 6,
    background: theme.colors.white,
    height: 50,
    "&:focus": {
      border: `1px solid ${theme.colors.gold}`,
    },
  },
  label: {
    marginBottom: "5px",
    color: "#64748B",
    fontSize: "18px",
    fontWeight: 700,
  },
};

// Form Field Groups
const formFields: { generalInfo: FieldGroup[]; roomsInfo: FieldGroup[] } = {
  generalInfo: [
    {
      type: "input",
      fields: [
        { label: "عدد المساكن", placeholder: "أدخل عدد المساكن" },
        { label: "رمز السكن", placeholder: "أدخل رمز السكن" },
      ],
    },
    {
      type: "input",
      fields: [
        { label: "اسم السكن في العرض", placeholder: "أدخل اسم السكن" },
        { label: "اسم السكن المختصر", placeholder: "أدخل الاسم المختصر" },
      ],
    },
    {
      type: "input",
      fields: [
        { label: "مساحة المسكن", placeholder: "أدخل المساحة" },
        { label: "المدينة", placeholder: "أدخل المدينة" },
      ],
    },
    {
      type: "input",
      fields: [
        { label: "المنطقة", placeholder: "أدخل المنطقة" },
        { label: "الحي", placeholder: "أدخل الحي" },
        { label: "الشارع", placeholder: "أدخل الشارع" },
      ],
    },
    {
      type: "input",
      fields: [
        {
          label: "خرائط جوجل",
          placeholder: "أدخل الموقع",
          rightSection: <IconMapPin size={16} />,
        },
      ],
    },
    {
      type: "input",
      fields: [
        { label: "وقت تسجيل الدخول", placeholder: "أدخل وقت الدخول" },
        { label: "وقت تسجيل الخروج", placeholder: "أدخل وقت الخروج" },
      ],
    },
  ],
  roomsInfo: [
    {
      type: "input",
      fields: [
        { label: "عدد الأسرة 1", placeholder: "أدخل العدد" },
        { label: "عدد الأسرة 2", placeholder: "أدخل العدد" },
        { label: "عدد الأسرة 3", placeholder: "أدخل العدد" },
      ],
    },
    {
      type: "select",
      fields: [
        {
          label: "عدد الصالات",
          placeholder: "اختر العدد",
          data: ["1", "2", "3", "4", "5"],
        },
        {
          label: "عدد الغرف",
          placeholder: "اختر العدد",
          data: ["1", "2", "3", "4", "5", "6", "7", "8"],
        },
      ],
    },
    {
      type: "select",
      fields: [
        {
          label: "عدد المطابخ",
          placeholder: "اختر العدد",
          data: ["1", "2", "3"],
        },
        {
          label: "عدد دورات المياه",
          placeholder: "اختر العدد",
          data: ["1", "2", "3", "4", "5"],
        },
      ],
    },
    {
      type: "select",
      fields: [
        {
          label: "جلسة الطعام",
          placeholder: "اختر العدد",
          data: ["1", "2", "3"],
        },
        {
          label: "عدد الكراسي",
          placeholder: "اختر العدد",
          data: ["2", "4", "6", "8", "10"],
        },
      ],
    },
    {
      type: "select",
      fields: [
        {
          label: "الحد الأقصى للضيوف",
          placeholder: "اختر العدد",
          data: ["2", "4", "6", "8", "10", "12", "14", "16"],
        },
        {
          label: "الحد الأقصى لعدد الليالي",
          placeholder: "اختر العدد",
          data: ["1", "2", "3", "4", "5", "6", "7", "14", "30"],
        },
      ],
    },
  ],
};

export default function NewProperty() {
  const router = useRouter();
  const [active, setActive] = useState(0);
  const [selectedType, setSelectedType] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [uploadedImages, setUploadedImages] = useState<UploadedFile[]>([]);
  const [uploadedVideos, setUploadedVideos] = useState<UploadedFile[]>([]);
  const [formData, setFormData] = useState<PropertyFormData>({
    type: "apartment",
    house_code: "",
    house_name: "",
    house_short_name: "",
    house_space: "",
    city_id: "1",
    area: "",
    neighborhood: "",
    longitude: "",
    latitude: "",
    basic_login_time: "",
    basic_logout_time: "",
    number_of_halls: "",
    number_of_rooms: "",
    number_of_bathrooms: "",
    number_of_chairs: "",
    number_of_kitchens: "",
    dining_session: "",
    maximum_guests: "",
    maximum_number_of_nights: "",
  });
  const [loading, setLoading] = useState(false);
  const [existingProperties, setExistingProperties] = useState<any[]>([]);

  useEffect(() => {
    if (selectedType === "existing") {
      fetchExistingProperties();
    }
  }, [selectedType]);

  const fetchExistingProperties = async () => {
    const token = Cookies.get("auth_token");
    if (!token) return;

    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/houses`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      const data = await response.json();
      if (data.success) {
        setExistingProperties(data.houses.data || []);
      }
    } catch (error) {
      console.error("Error fetching properties:", error);
      notifications.show({
        title: "خطأ",
        message: "حدث خطأ أثناء جلب المساكن الموجودة",
        color: "red",
      });
    }
  };

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

  const validateForm = () => {
    const requiredFields = [
      "house_code",
      "house_name",
      "house_short_name",
      "house_space",
      "area",
      "neighborhood",
    ];

    const missingFields = requiredFields.filter((field) => !formData[field]);

    if (missingFields.length > 0) {
      notifications.show({
        title: "خطأ",
        message: "يرجى ملء جميع الحقول المطلوبة",
        color: "red",
      });
      return false;
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    setLoading(true);
    const token = Cookies.get("auth_token");
    if (!token) {
      notifications.show({
        title: "خطأ",
        message: "يرجى تسجيل الدخول أولاً",
        color: "red",
      });
      return;
    }

    try {
      const formDataToSend = new FormData();
      Object.entries(formData).forEach(([key, value]) => {
        formDataToSend.append(key, value);
      });

      if (uploadedImages.length > 0) {
        formDataToSend.append("image", uploadedImages[0].file);
      }
      if (uploadedVideos.length > 0) {
        formDataToSend.append("video", uploadedVideos[0].file);
      }

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/houses`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
          body: formDataToSend,
        }
      );

      const data = await response.json();

      if (data.success) {
        notifications.show({
          title: "نجاح",
          message: "تم إضافة المسكن بنجاح",
          color: "green",
        });
        router.push("/properties");
      } else {
        throw new Error(data.message || "حدث خطأ أثناء إضافة المسكن");
      }
    } catch (error: any) {
      notifications.show({
        title: "خطأ",
        message: error.message || "حدث خطأ أثناء إضافة المسكن",
        color: "red",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleAddClick = () => {
    setShowForm(true);
  };

  const handleFileUpload = (
    event: React.ChangeEvent<HTMLInputElement>,
    type: "image" | "video"
  ) => {
    const files = event.target.files;
    if (files) {
      const newFiles: UploadedFile[] = [];
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const reader = new FileReader();
        reader.onloadend = () => {
          const preview = reader.result as string;
          const size = formatFileSize(file.size);
          const id = Date.now() + i;
          const uploadedFile: UploadedFile = {
            file,
            preview,
            size,
            id,
          };
          if (type === "image") {
            setUploadedImages((prevImages) => [...prevImages, uploadedFile]);
          } else {
            setUploadedVideos((prevVideos) => [...prevVideos, uploadedFile]);
          }
        };
        reader.readAsDataURL(file);
      }
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  const handleCancel = () => {
    setShowForm(false);
  };

  // Move CustomInput inside the component
  const CustomInput = ({
    label,
    placeholder,
    rightSection,
    name,
    ...props
  }: InputField & { name: string }) => (
    <TextInput
      label={label}
      placeholder={placeholder}
      size="lg"
      mt="md"
      rightSection={rightSection}
      styles={inputStyles}
      value={formData[name] || ""}
      onChange={(e) => handleInputChange(name, e.target.value)}
      {...props}
    />
  );

  // Move CustomSelect inside the component
  const CustomSelect = ({
    label,
    placeholder,
    data,
    name,
    ...props
  }: SelectField & { name: string }) => (
    <Select
      label={label}
      placeholder={placeholder}
      size="lg"
      rightSection={<IconChevronDown size={16} />}
      data={data}
      styles={inputStyles}
      value={formData[name] || ""}
      onChange={(value) => handleInputChange(name, value || "")}
      {...props}
    />
  );

  // Move FieldGroup inside the component
  const FieldGroup = ({ fields, type }: FieldGroup) => (
    <Flex gap="md" wrap="wrap">
      {fields.map((field, index: number) => (
        <Box key={index} style={{ flex: 1 }} className={styles.FieldGroup}>
          {type === "input" ? (
            <CustomInput {...(field as InputField & { name: string })} />
          ) : (
            <CustomSelect {...(field as SelectField & { name: string })} />
          )}
        </Box>
      ))}
    </Flex>
  );

  // Move UploadedItem inside the component
  const UploadedItem = ({
    file,
    type = "image",
  }: {
    file: UploadedFile;
    type: "image" | "video";
  }) => {
    return (
      <Flex align="center" justify="space-between" gap="md" mt="md" w="100%">
        <Flex align="center" gap="md">
          <IconList size={24} color="#64748B" />
          {type === "image" ? (
            <Image
              src={file.preview}
              alt={file.file.name}
              width={120}
              height={120}
              style={{ borderRadius: "8px", objectFit: "cover" }}
            />
          ) : (
            <Box
              w={120}
              h={120}
              style={{
                background: "#F4F6F9",
                borderRadius: "8px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <IconVideo size={32} color="#64748B" />
            </Box>
          )}
          <Stack gap={4}>
            <Text size="sm" c="#64748B">
              {file.file.name}
            </Text>
            <Text size="sm" c="#64748B">
              الحجم: {formatFileSize(file.file.size)}
            </Text>
          </Stack>
        </Flex>
        <Chip
          color="#CFC07B"
          styles={{
            root: {
              color: "white",
            },
          }}
        >
          الترتيب: {file.id}
        </Chip>
      </Flex>
    );
  };

  if (!showForm) {
    return (
      <Box p="xl">
        <Paper
          p="xl"
          radius="md"
          style={{
            backgroundColor: "white",
            maxWidth: "1200px",
            margin: "0 auto",
          }}
          w="100%"
        >
          <Box ta="center">
            <Text size="xl" fw={700} mb={8}>
              اضافة مسكن جديد
            </Text>

            <Text c="dimmed" mb={32}>
              قم باختيار نوع السكن
            </Text>

            <Flex justify="center" gap="md" mb={32} w="100%">
              <Box
                w={{ base: "100%", md: "50%" }}
                p="xl"
                style={{
                  backgroundColor:
                    selectedType === "new" ? "#CFC07B" : "#F4F6F9",
                  borderRadius: "8px",
                  cursor: "pointer",
                  transition: "all 0.2s ease",
                  color: selectedType === "new" ? "white" : "#9094A0",
                }}
                onClick={() => setSelectedType("new")}
              >
                <Text ta="center" fw={500}>
                  مسكن جديد
                </Text>
              </Box>

              <Box
                w={{ base: "100%", md: "50%" }}
                p="xl"
                style={{
                  backgroundColor:
                    selectedType === "existing" ? "#CFC07B" : "#F4F6F9",
                  borderRadius: "8px",
                  cursor: "pointer",
                  transition: "all 0.2s ease",
                  color: selectedType === "existing" ? "white" : "#9094A0",
                }}
                onClick={() => setSelectedType("existing")}
              >
                <Text ta="center" fw={500}>
                  مسكن تم انشاؤه مسبقا
                </Text>
              </Box>
            </Flex>

            {selectedType === "existing" && existingProperties.length > 0 && (
              <Box mb="xl">
                <Text size="lg" fw={500} mb="md">
                  اختر من المساكن الموجودة
                </Text>
                <Select
                  data={existingProperties.map((prop) => ({
                    value: prop.id.toString(),
                    label: prop.house_name,
                  }))}
                  placeholder="اختر مسكن"
                  onChange={(value) => {
                    if (value) {
                      const selectedProperty = existingProperties.find(
                        (p) => p.id.toString() === value
                      );
                      if (selectedProperty) {
                        setFormData({
                          ...formData,
                          house_code: selectedProperty.house_code,
                          house_name: selectedProperty.house_name,
                          house_short_name: selectedProperty.house_short_name,
                          house_space: selectedProperty.house_space,
                          area: selectedProperty.area,
                          neighborhood: selectedProperty.neighborhood,
                        });
                        setShowForm(true);
                      }
                    }
                  }}
                />
              </Box>
            )}

            <Button
              w={{ base: "100%", md: "30%" }}
              style={{
                backgroundColor: "#8C8082",
                color: "white",
              }}
              size="xl"
              radius="md"
              onClick={handleAddClick}
              disabled={
                selectedType === "existing" && existingProperties.length === 0
              }
            >
              {selectedType === "existing" ? "اختر مسكن" : "اضافة"}
            </Button>
          </Box>
        </Paper>
      </Box>
    );
  }

  return (
    <Box p="xl">
      <Stepper
        p={{ base: "sm", md: 50 }}
        dir="ltr"
        active={active}
        onStepClick={setActive}
        color="#CFC07B"
        styles={(theme) => ({
          stepBody: {
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            marginTop: "10px",
          },
          stepIcon: {
            borderColor: "#CFC07B",
            width: "40px",
            height: "40px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            "&[dataCompleted]": {
              backgroundColor: "#CFC07B",
              borderColor: "#CFC07B",
              color: "white",
            },
            "&[dataProgress]": {
              backgroundColor: "#CFC07B",
              borderColor: "#CFC07B",
              color: "white",
            },
            "&[dataActive]": {
              backgroundColor: "#CFC07B",
              borderColor: "#CFC07B",
              color: "white",
            },
            "&[dataActive] svg": {
              color: "white",
            },
          },
          stepLabel: {
            marginTop: "8px",
            fontSize: "14px",
            fontWeight: 500,
            color: "#64748B",
          },
        })}
      >
        <Stepper.Step label="معلومات السكن" icon={<IconHome size={20} />} />
        <Stepper.Step label="السعر" icon={<IconCurrencyDollar size={20} />} />
        <Stepper.Step label="معلومات الدخول" icon={<IconLogin size={20} />} />
        <Stepper.Step label="العرض والتأكيد" icon={<IconCheck size={20} />} />
      </Stepper>

      {active === 0 && (
        <Box mt="xl">
          <Text size="xl" fw={700} mb="xl">
            معلومات عامة عن السكن
          </Text>

          <Stack gap="md">
            {formFields.generalInfo.map((group, index) => (
              <FieldGroup key={index} {...group} />
            ))}

            <Text size="xl" fw={700} mt="xl" mb="xl">
              الصالات والغرف
            </Text>

            {formFields.roomsInfo.map((group, index) => (
              <FieldGroup key={index} {...group} />
            ))}

            <Text size="xl" fw={700} mt="xl" mb="xl">
              الصور والمرفقات
            </Text>

            <Text mb="md">صورة العرض الرئيسية</Text>

            <Box
              w="10%"
              style={{
                borderRadius: "15px",
                background: "#8C8082",
                padding: "2rem",
                cursor: "pointer",
                textAlign: "center",
              }}
              component="label"
              className={styles.boxField}
            >
              <input
                type="file"
                accept="image/*"
                style={{ display: "none" }}
                onChange={(e) => handleFileUpload(e, "image")}
              />
              <Stack align="center" gap="md">
                <IconUpload size={32} color="white" />
                <Text c="white">رفع صور المسكن</Text>
              </Stack>
            </Box>

            {uploadedImages.length > 0 && (
              <Box mt="xl">
                <Text mb="md" fw={700} size="lg">
                  الصور
                </Text>
                <Stack gap="md">
                  {uploadedImages.map((image) => (
                    <UploadedItem key={image.id} file={image} type="image" />
                  ))}
                </Stack>
              </Box>
            )}

            <Text mt="xl" mb="md" fw={700} size="lg">
              الفيديو
            </Text>
            <Box
              w="10%"
              style={{
                borderRadius: "15px",
                background: "#8C8082",
                padding: "2rem",
                cursor: "pointer",
                textAlign: "center",
              }}
              component="label"
              className={styles.boxField}
            >
              <input
                type="file"
                accept="video/*"
                style={{ display: "none" }}
                onChange={(e) => handleFileUpload(e, "video")}
              />
              <Stack align="center" gap="md">
                <IconVideo size={32} color="white" />
                <Text c="white">رفع فيديو المسكن</Text>
              </Stack>
            </Box>

            {uploadedVideos.length > 0 && (
              <Box mt="xl">
                <Stack gap="md">
                  {uploadedVideos.map((video) => (
                    <UploadedItem key={video.id} file={video} type="video" />
                  ))}
                </Stack>
              </Box>
            )}
          </Stack>

          <Flex gap="md" mt="xl" justify="center">
            <Button
              radius="md"
              size="lg"
              w="50%"
              onClick={() => setActive(1)}
              style={{
                backgroundColor: "#8C8082",
                color: "white",
              }}
            >
              التالي
            </Button>
            <Button
              radius="md"
              w="50%"
              size="lg"
              onClick={handleCancel}
              variant="outline"
              style={{
                backgroundColor: "#FFF",
                border: "1px solid #E2E8F0",
                color: "#64748B",
              }}
            >
              الغاء
            </Button>
          </Flex>
        </Box>
      )}

      {active === 1 && (
        <Box mt="xl">
          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            السعر
          </Text>
          {[...Array(3)].map((_, i) => (
            <Flex gap="md" wrap="wrap" mb="md" key={i} w="100%">
              <Box style={{ flex: 1 }}>
                <CustomInput
                  label="اليوم"
                  placeholder="أدخل اليوم"
                  name="day"
                />
              </Box>
              <Box style={{ flex: 1 }}>
                <CustomInput
                  label="السعر"
                  placeholder="أدخل السعر"
                  name="price"
                />
              </Box>
            </Flex>
          ))}

          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            المناسبات
          </Text>
          {[...Array(3)].map((_, i) => (
            <Flex gap="md" wrap="wrap" mb="md" key={i}>
              <Box style={{ flex: 1 }}>
                <CustomInput
                  label="المناسبة"
                  placeholder="أدخل المناسبة"
                  name="event"
                />
              </Box>
              <Box style={{ flex: 1 }}>
                <CustomInput
                  label="السعر"
                  placeholder="أدخل السعر"
                  name="event_price"
                />
              </Box>
            </Flex>
          ))}

          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            العربون
          </Text>
          <Group>
            <Chip value="accept" variant="outline" color="gold" radius="md">
              قبول العربون
            </Chip>
            <Chip value="reject" variant="outline" color="gold" radius="md">
              رفض العربون
            </Chip>
          </Group>

          <Box mt="md" mb="xl">
            <CustomSelect
              label="العربون"
              placeholder="نسبة العربون"
              data={["10%", "20%", "30%", "50%"]}
              name="commission_percentage"
            />
          </Box>

          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            الخصومات
          </Text>
          <CustomSelect
            label="الخصم"
            placeholder="نوع الخصم"
            data={["نقدي", "موسمي", "رمزي"]}
            name="discount_type"
          />

          <Flex gap="md" wrap="wrap" mt="md" mb="xl">
            <Box style={{ flex: 1 }}>
              <CustomInput
                label="النسبة"
                placeholder="أدخل النسبة"
                name="discount_percentage"
              />
            </Box>
            <Box style={{ flex: 1 }}>
              <CustomInput
                label="القيمة"
                placeholder="أدخل القيمة"
                name="discount_value"
              />
            </Box>
          </Flex>

          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            إعدادات الدخول المبكر والخروج المتأخر
          </Text>

          <Flex justify="space-between" align="center" mb="lg">
            <Text>الدخول المبكر</Text>
            <Switch color={theme.colors.gold} size="md" />
          </Flex>

          <Flex justify="space-between" align="center" mb="xl">
            <Text>الخروج المتأخر</Text>
            <Switch color={theme.colors.gold} size="md" />
          </Flex>

          <Text c="#8C8082" fw={700} size="xl" mb="md" mt="xl">
            الحد الأدنى لعدد الليالي
          </Text>
          <CustomSelect
            label="الحد الادني لعدد الليالي"
            placeholder="اختر العدد"
            data={["1", "2", "3", "4", "5", "6", "7", "10", "14"]}
            name="minimum_number_of_nights"
          />

          <Flex gap="md" mt="xl" justify="center">
            <Button
              radius="md"
              size="lg"
              w="50%"
              onClick={() => setActive(2)}
              style={{
                backgroundColor: "#8C8082",
                color: "white",
              }}
            >
              التالي
            </Button>
            <Button
              radius="md"
              w="50%"
              size="lg"
              onClick={() => setActive(0)}
              variant="outline"
              style={{
                backgroundColor: "#FFF",
                border: "1px solid #E2E8F0",
                color: "#64748B",
              }}
            >
              رجوع
            </Button>
          </Flex>
        </Box>
      )}

      {active === 2 && (
        <Box mt="xl">
          <Text c="#8C8082" fw={700} size="xl" mb="md">
            معلومات تسجيل الدخول
          </Text>

          <TextInput
            label="معلومات تسجيل الدخول"
            placeholder="أدخل تفاصيل الدخول"
            size="lg"
            styles={inputStyles}
            mt="md"
          />

          <Checkbox
            color={theme.colors.gold}
            label="سيتم التواصل مع الضيف مباشرة"
            size="md"
            mt="md"
          />
          <Checkbox
            color={theme.colors.gold}
            label="اختيار وقت ظهور تعليمات الدخول للضيف"
            size="md"
            mt="sm"
          />

          <Flex gap="md" wrap="wrap" mt="md">
            <Box style={{ flex: 1 }}>
              <CustomSelect
                label="وقت الدخول"
                placeholder="اختر الوقت"
                data={["12:00", "14:00", "16:00", "18:00"]}
                name="login_time"
              />
            </Box>
            <Box style={{ flex: 1 }}>
              <CustomSelect
                label="وقت الظهور"
                placeholder="اختر الوقت"
                data={[
                  "قبل الوصول بـ 24 ساعة",
                  "قبل الوصول بـ 12 ساعة",
                  "عند الوصول",
                ]}
                name="notification_time"
              />
            </Box>
          </Flex>

          <TextInput
            label="تعليمات صوتية لتسجيل الدخول"
            placeholder="مثال: قم بإدخال الرمز بعد سماع الصافرة"
            size="lg"
            rightSection={<IconVideo size={20} />}
            styles={inputStyles}
            mt="md"
          />

          <CustomInput
            label="اسم الشبكة"
            placeholder="أدخل اسم شبكة الواي فاي"
            name="wifi_network"
          />

          <CustomInput
            label="كلمة المرور"
            placeholder="أدخل كلمة مرور الشبكة"
            name="wifi_password"
          />

          <Flex gap="md" wrap="wrap" mt="md">
            <Box style={{ flex: 1 }}>
              <CustomInput
                label="رمز بوابة 1"
                placeholder="أدخل الرمز"
                name="access_code_1"
              />
            </Box>
            <Box style={{ flex: 1 }}>
              <CustomSelect
                label="وقت الظهور"
                placeholder="اختر الوقت"
                data={[
                  "عند الوصول",
                  "قبل الوصول بـ 1 ساعة",
                  "قبل الوصول بـ 12 ساعة",
                ]}
                name="access_code_1_time"
              />
            </Box>
          </Flex>

          <TextInput
            label="مميزات السكن"
            placeholder="أدخل المميزات"
            size="lg"
            styles={inputStyles}
            mt="md"
          />

          <TextInput
            label="التعليمات والتحذيرات"
            placeholder="أدخل التعليمات"
            size="lg"
            styles={inputStyles}
            mt="md"
          />

          <CustomInput
            label="رقم التواصل 1"
            placeholder="أدخل رقم التواصل"
            name="contact_1"
          />

          <CustomInput
            label="رقم التواصل 2"
            placeholder="أدخل رقم التواصل"
            name="contact_2"
          />

          <Flex gap="md" mt="xl" justify="center">
            <Button
              radius="md"
              size="lg"
              w="50%"
              onClick={() => setActive(3)}
              style={{
                backgroundColor: "#8C8082",
                color: "white",
              }}
            >
              التالي
            </Button>
            <Button
              radius="md"
              w="50%"
              size="lg"
              onClick={() => setActive(1)}
              variant="outline"
              style={{
                backgroundColor: "#FFF",
                border: "1px solid #E2E8F0",
                color: "#64748B",
              }}
            >
              رجوع
            </Button>
          </Flex>
        </Box>
      )}

      {active === 3 && (
        <Flex gap="md" mt="xl" justify="center">
          <Button
            radius="md"
            size="lg"
            w="50%"
            onClick={handleSubmit}
            loading={loading}
            style={{
              backgroundColor: "#8C8082",
              color: "white",
            }}
          >
            حفظ
          </Button>
          <Button
            radius="md"
            w="50%"
            size="lg"
            onClick={() => setActive(2)}
            variant="outline"
            style={{
              backgroundColor: "#FFF",
              border: "1px solid #E2E8F0",
              color: "#64748B",
            }}
          >
            رجوع
          </Button>
        </Flex>
      )}
    </Box>
  );
}
