import React, { useState } from "react";
import {
  Paper,
  Stack,
  TextInput,
  Select,
  NumberInput,
  Checkbox,
  Table,
  Badge,
  Button,
  Modal,
  Textarea,
  Group,
  Text,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import type { ResortUnit } from "@/lib/features/resorts/types";

interface ResortInventoryPanelProps {
  units: ResortUnit[];
  setUnits: React.Dispatch<React.SetStateAction<ResortUnit[]>>;
  unitTypes: string[];
  canEdit: boolean;
  sectionTitle: (title: string) => React.ReactNode;
}

export const ResortInventoryPanel: React.FC<ResortInventoryPanelProps> = ({
  units,
  setUnits,
  unitTypes,
  canEdit,
  sectionTitle,
}) => {
  const [editingUnit, setEditingUnit] = useState<ResortUnit | null>(null);
  const [unitModalOpened, { open: openUnitModal, close: closeUnitModal }] = useDisclosure(false);

  const updateUnit = (id: string, field: keyof ResortUnit, val: any) =>
    setUnits((prev) => prev.map((u) => (u.id === id ? { ...u, [field]: val } : u)));

  const handleEditUnitDetails = (unit: ResortUnit) => {
    setEditingUnit(unit);
    openUnitModal();
  };

  const handleSaveUnitModal = () => {
    if (!editingUnit) return;
    closeUnitModal();
    notifications.show({ color: "green", message: "Unit details updated successfully" });
  };

  return (
    <Paper withBorder radius="md" p="lg">
      {sectionTitle("Section 4 — Resort Inventory & Accommodations")}
      <Stack gap="md">
        {units.length > 0 && (
          <Table withTableBorder withColumnBorders style={{ fontFamily: "Outfit, Inter, sans-serif" }}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Unit Name *</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>VP Code *</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Type</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Total Occ.</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Adult</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Children</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Child</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Active</Table.Th>
                <Table.Th style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Channels</Table.Th>
                <Table.Th style={{ width: 140, fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>Actions</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {units.map((unit) => (
                <Table.Tr key={unit.id}>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <TextInput
                      value={unit.unit_name}
                      onChange={(e) => updateUnit(unit.id, "unit_name", e.currentTarget.value)}
                      readOnly={!canEdit}
                      size="sm"
                      placeholder="Unit name"
                      disabled
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <TextInput
                      value={unit.unit_vp_code}
                      onChange={(e) => updateUnit(unit.id, "unit_vp_code", e.currentTarget.value)}
                      readOnly={!canEdit}
                      size="sm"
                      placeholder="VP code"
                      disabled
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <Select
                      value={unit.unit_type ?? null}
                      onChange={(v) => updateUnit(unit.id, "unit_type", v)}
                      data={unitTypes}
                      disabled={!canEdit}
                      size="sm"
                      clearable
                      style={{ width: 160 }}
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <NumberInput
                      value={unit.total_occupancy ?? ""}
                      onChange={(v) => updateUnit(unit.id, "total_occupancy", v === "" ? null : Number(v))}
                      readOnly={!canEdit}
                      size="xs"
                      min={0}
                      style={{ width: 80 }}
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <NumberInput
                      value={unit.adult_occupancy ?? ""}
                      onChange={(v) => updateUnit(unit.id, "adult_occupancy", v === "" ? null : Number(v))}
                      readOnly={!canEdit}
                      size="xs"
                      min={0}
                      style={{ width: 80 }}
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <NumberInput
                      value={unit.children_occupancy ?? ""}
                      onChange={(v) => updateUnit(unit.id, "children_occupancy", v === "" ? null : Number(v))}
                      readOnly={!canEdit}
                      size="xs"
                      min={0}
                      style={{ width: 80 }}
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <NumberInput
                      value={unit.child_occupancy ?? ""}
                      onChange={(v) => updateUnit(unit.id, "child_occupancy", v === "" ? null : Number(v))}
                      readOnly={!canEdit}
                      size="xs"
                      min={0}
                      style={{ width: 80 }}
                      styles={{ input: { fontFamily: "Outfit, Inter, sans-serif" } }}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <Checkbox
                      checked={unit.is_active}
                      onChange={(e) => updateUnit(unit.id, "is_active", e.currentTarget.checked)}
                      disabled={!canEdit}
                    />
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle" }}>
                    <Stack gap="xs">
                      <Checkbox
                        label="Hot Deals"
                        checked={unit.eligible_for_hot_deals}
                        onChange={(e) => updateUnit(unit.id, "eligible_for_hot_deals", e.currentTarget.checked)}
                        disabled={!canEdit}
                        size="xs"
                        styles={{ label: { fontFamily: "Outfit, Inter, sans-serif", fontWeight: 500 } }}
                      />
                      <Checkbox
                        label="Excl. Discovery"
                        checked={unit.eligible_for_exclusive_discovery}
                        onChange={(e) => updateUnit(unit.id, "eligible_for_exclusive_discovery", e.currentTarget.checked)}
                        disabled={!canEdit}
                        size="xs"
                        styles={{ label: { fontFamily: "Outfit, Inter, sans-serif", fontWeight: 500 } }}
                      />
                    </Stack>
                  </Table.Td>
                  <Table.Td style={{ verticalAlign: "middle", textAlign: "center" }}>
                    <Button
                      size="compact-xs"
                      variant="light"
                      onClick={() => handleEditUnitDetails(unit)}
                      styles={{
                        root: {
                          fontFamily: "Outfit, Inter, sans-serif",
                          fontWeight: 500,
                          margin: "0 auto",
                        },
                      }}
                    >
                      Details & Media
                    </Button>
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        )}
        {units.length === 0 && (
          <Text size="sm" c="dimmed" style={{ fontFamily: "Outfit, Inter, sans-serif" }}>
            No units yet. Click "Add Unit" to add inventory.
          </Text>
        )}
      </Stack>

      {/* Unit details modal */}
      <Modal
        opened={unitModalOpened}
        onClose={closeUnitModal}
        title={`Edit Unit Media & Details: ${editingUnit?.unit_name || editingUnit?.unit_vp_code}`}
        size="lg"
        centered
      >
        {editingUnit && (
          <Stack gap="md">
            <Textarea
              label="Unit Description"
              placeholder="Describe the accommodation room, bedding, amenities, etc."
              value={editingUnit.description ?? ""}
              onChange={(e) => {
                const newVal = e.currentTarget.value;
                setEditingUnit((prev) => (prev ? { ...prev, description: newVal } : null));
                updateUnit(editingUnit.id, "description", newVal);
              }}
              readOnly={!canEdit}
              minRows={3}
            />

            <TextInput
              label="Featured Image URL"
              placeholder="https://example.com/image.jpg"
              value={editingUnit.featured_image ?? ""}
              onChange={(e) => {
                const newVal = e.currentTarget.value;
                setEditingUnit((prev) => (prev ? { ...prev, featured_image: newVal } : null));
                updateUnit(editingUnit.id, "featured_image", newVal);
              }}
              readOnly={!canEdit}
            />
            {editingUnit.featured_image && (
              <Paper withBorder p="xs" style={{ display: "inline-block", maxWidth: 200 }}>
                <img
                  src={editingUnit.featured_image}
                  alt="Featured Preview"
                  style={{ width: "100%", maxHeight: 120, objectFit: "cover", borderRadius: "4px" }}
                />
              </Paper>
            )}

            <div>
              <Text size="sm" fw={500} mb={4}>
                Gallery Images (One URL per line)
              </Text>
              <Textarea
                placeholder="https://example.com/img1.jpg&#10;https://example.com/img2.jpg"
                value={(editingUnit.images ?? []).join("\n")}
                onChange={(e) => {
                  const urls = e.currentTarget.value
                    .split("\n")
                    .map((s) => s.trim())
                    .filter(Boolean);
                  setEditingUnit((prev) => (prev ? { ...prev, images: urls } : null));
                  updateUnit(editingUnit.id, "images", urls);
                }}
                readOnly={!canEdit}
                minRows={4}
              />
            </div>

            {(editingUnit.images ?? []).length > 0 && (
              <Stack gap="xs">
                <Text size="xs" fw={500} c="dimmed">
                  Gallery Previews
                </Text>
                <Group gap="xs">
                  {(editingUnit.images ?? []).map((img, i) => (
                    <Paper key={i} withBorder p="2px" style={{ width: 80, height: 60 }}>
                      <img
                        src={img}
                        alt={`Gallery Preview ${i}`}
                        style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "2px" }}
                      />
                    </Paper>
                  ))}
                </Group>
              </Stack>
            )}

            <Group justify="flex-end" mt="md">
              <Button variant="subtle" onClick={closeUnitModal}>
                Cancel
              </Button>
              <Button onClick={handleSaveUnitModal} disabled={!canEdit}>
                Save Unit Details
              </Button>
            </Group>
          </Stack>
        )}
      </Modal>
    </Paper>
  );
};
