"use client";

import {
  Box,
  Card,
  Text,
  Group,
  TextInput,
  Paper,
  Button,
  ActionIcon,
  SimpleGrid,
  Image,
} from "@mantine/core";
import {
  IconBuilding,
  IconSearch,
  IconFilter,
  IconPrinter,
  IconColumns,
  IconLayoutGrid,
  IconLayoutList,
  IconMapPin,
  IconBed,
  IconBath,
  IconUsers,
} from "@tabler/icons-react";
import theme from "../../../styles/theme";
import { AddPropertyModal } from "@/shared/AddPropertyModal";
import { ErrorModal } from "@/shared/ErrorModal";
import { useEffect, useState } from "react";
import Cookies from "js-cookie";

const stats = [
  {
    title: "178",
    description: "عدد المساكن",
    icon: IconBuilding,
    color: theme.colors.gold,
  },
];

const filterOptions = [
  { label: "فلترة", icon: IconFilter },
  { label: "طباعة", icon: IconPrinter },
  { label: "اخفاء اعمدة", icon: IconColumns },
];

export default function Properties() {
  const [modalOpened, setModalOpened] = useState(false);
  const [errorModalOpened, setErrorModalOpened] = useState(false);
  const [properties, setProperties] = useState<any[]>([]);

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

      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/houses`,
          {
            method: "GET",
            headers: {
              Authorization: `Bearer ${token}`,
              "Content-Type": "application/json",
            },
          }
        );

        const data = await response.json();

        if (response.ok && data.success) {
          setProperties(data.houses.data || []);
        } else {
          console.error("Failed to load houses:", data.message);
        }
      } catch (error) {
        console.error("Fetch error:", error);
      }
    };

    fetchHouses();
  }, []);

  return (
    <Box p="xl">
      <AddPropertyModal
        opened={modalOpened}
        onClose={() => setModalOpened(false)}
      />
      <ErrorModal
        opened={errorModalOpened}
        onClose={() => setErrorModalOpened(false)}
      />

      <Card
        padding="lg"
        radius="md"
        shadow="xs"
        style={{
          backgroundColor: "white",
          transition: "transform 0.2s ease",
          "&:hover": {
            transform: "translateY(-5px)",
          },
        }}
      >
        <Group>
          <Box
            style={{
              backgroundColor: `${stats[0].color}15`,
              padding: "12px",
              borderRadius: "12px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <IconBuilding size={24} color={stats[0].color} />
          </Box>
          <Box>
            <Text fw={700} size="xl" c="black">
              {stats[0].title}
            </Text>
            <Text size="sm" c="dimmed">
              {stats[0].description}
            </Text>
          </Box>
        </Group>
      </Card>

      <Box mt="xl">
        <TextInput
          size="lg"
          placeholder="بحث"
          mb="xl"
          rightSection={<IconSearch size={20} color={theme.colors.darkGray} />}
          styles={{
            input: {
              backgroundColor: "white",
              border: "none",
            },
          }}
        />
        <Group justify="space-between" align="center">
          <Group>
            <Group gap="xs">
              {filterOptions.map((option, index) => (
                <Paper
                  key={index}
                  p="xs"
                  style={{
                    backgroundColor: "white",
                    display: "flex",
                    alignItems: "center",
                    gap: "8px",
                    cursor: "pointer",
                  }}
                >
                  <option.icon size={16} color={theme.colors.darkGray} />
                  <Text size="sm">{option.label}</Text>
                </Paper>
              ))}
            </Group>
          </Group>

          <Group>
            <Button
              style={{
                backgroundColor: "#8C8082",
                borderRadius: "16px",
              }}
              onClick={() => setModalOpened(true)}
            >
              اضافة سكن جديد
            </Button>

            <Group gap="xs">
              <ActionIcon
                variant="transparent"
                style={{
                  backgroundColor: "#CFC07B",
                  color: "white",
                }}
              >
                <IconLayoutGrid size={20} />
              </ActionIcon>
              <ActionIcon variant="transparent">
                <IconLayoutList size={20} color={theme.colors.darkGray} />
              </ActionIcon>
            </Group>
          </Group>
        </Group>
      </Box>

      <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="lg" mt="xl">
        {properties.length > 0 ? (
          properties.map((property) => (
            <Card
              key={property.id}
              padding="lg"
              radius="md"
              shadow="xs"
              pos="relative"
            >
              <Paper
                pos="absolute"
                top={16}
                left={16}
                px="md"
                py="xs"
                radius={25.888}
                style={{ backgroundColor: "#07901C", zIndex: 1 }}
              >
                <Text size="sm" c="white">
                  {property.status || "غير محدد"}
                </Text>
              </Paper>

              <Group align="center" wrap="nowrap">
                <Image
                  src={property.image || "/images/image.png"}
                  alt={property.name}
                  w={200}
                  height={150}
                  radius={40}
                  mb={20}
                />
                <Box style={{ flex: 1 }}>
                  <Text fw={700} size="lg" mb="xs">
                    {property.name}
                  </Text>
                  <Text size="sm" c="dimmed" mb="xs">
                    {property.shortName || "بدون نوع"}
                  </Text>
                  <Group gap="xs" mb="md">
                    <IconMapPin size={16} color={theme.colors.gold} />
                    <Text size="sm">{property.location || "بدون موقع"}</Text>
                  </Group>
                  <Group gap="lg" mb="xl">
                    <Group gap="xs">
                      <IconBed size={16} color={theme.colors.darkGray} />
                      <Text size="sm">{property.beds ?? 0}</Text>
                    </Group>
                    <Group gap="xs">
                      <IconBath size={16} color={theme.colors.darkGray} />
                      <Text size="sm">{property.baths ?? 0}</Text>
                    </Group>
                    <Group gap="xs">
                      <IconUsers size={16} color={theme.colors.darkGray} />
                      <Text size="sm">{property.guests ?? 0}</Text>
                    </Group>
                  </Group>
                </Box>
              </Group>
              <Button
                fullWidth
                style={{
                  backgroundColor: "#CFC07B",
                  borderRadius: "5.04px",
                }}
                onClick={() => setErrorModalOpened(true)}
              >
                عرض التفاصيل
              </Button>
            </Card>
          ))
        ) : (
          <Text ta="center" mt="xl" c="dimmed">
            لا توجد مساكن حالياً
          </Text>
        )}
      </SimpleGrid>
    </Box>
  );
}
