import React from "react";
import {
  Paper,
  Stack,
  TextInput,
  Select,
  SimpleGrid,
  Switch,
  Group,
  ThemeIcon,
  Text,
  Checkbox,
  Table,
  Badge,
  NumberInput,
  MultiSelect,
  Radio,
  Tooltip,
  Button,
  Grid,
  Alert,
  Box,
} from "@mantine/core";
import { DateInput, DateTimePicker } from "@mantine/dates";
import { RichTextComp } from "@/components/Richtext";
import {
  IconTag,
  IconCalendar,
  IconSettings,
  IconSend,
  IconEdit,
  IconClock,
  IconCheck,
  IconLock,
  IconFileText,
  IconTrash,
  IconAlertCircle,
} from "@tabler/icons-react";
import moment from "moment";
import type {
  OfferType,
  PublishMode,
  AllowedUserType,
  OfferValueType,
} from "@/lib/features/member-offers/types";

export interface UnitOfferRow {
  resort_unit_id: string;
  unit_name: string;
  unit_vp_code: string;
  unit_type?: string;
  is_selected: boolean;
  is_admin_override: boolean;
  offer_value_type: OfferValueType | null;
  offer_value: number | "";
  minimum_nights: number | "";
  maximum_nights_per_booking: number | "";
  maximum_units_per_membership: number | "";
}

interface OfferConfigurationTabProps {
  offerName: string;
  setOfferName: (name: string) => void;
  offerType: OfferType;
  setOfferType: (type: OfferType) => void;
  resortId: string | null;
  handleResortChange: (val: string | null) => void;
  isActive: boolean;
  setIsActive: (val: boolean) => void;
  isCancellable: boolean;
  setIsCancellable: (val: boolean) => void;
  bookingStart: string | null;
  setBookingStart: (val: string | null) => void;
  bookingEnd: string | null;
  setBookingEnd: (val: string | null) => void;
  travelStart: string | null;
  setTravelStart: (val: string | null) => void;
  travelEnd: string | null;
  setTravelEnd: (val: string | null) => void;
  unitRows: UnitOfferRow[];
  updateUnitRow: (unitId: string, field: keyof UnitOfferRow, val: any) => void;
  availableToAdd: any[];
  selectedUnitToAdd: string | null;
  setSelectedUnitToAdd: (val: string | null) => void;
  handleAddUnit: () => void;
  deleteUnitRow: (unitId: string) => void;
  inclusions: string;
  setInclusions: (val: string) => void;
  blockedAccountTypes: string[];
  setBlockedAccountTypes: (val: string[]) => void;
  blockedAccountStatuses: string[];
  setBlockedAccountStatuses: (val: string[]) => void;
  blockedClubs: string[];
  setBlockedClubs: (val: string[]) => void;
  allowedUserTypes: AllowedUserType[];
  setAllowedUserTypes: React.Dispatch<React.SetStateAction<AllowedUserType[]>>;
  publishMode: PublishMode;
  setPublishMode: (mode: PublishMode) => void;
  scheduledPublishAt: string | null;
  setScheduledPublishAt: (val: string | null) => void;
  publishedAt?: string | null;
  rawConfig: Record<string, any>;
  setRawConfig: React.Dispatch<React.SetStateAction<Record<string, any>>>;
  resorts: { id: string; name: string }[];
  accountTypes: { id: string; label: string }[];
  accountStatuses: { id: string; label: string }[];
  clubs: { id: string; label: string }[];
  canEdit: boolean;
  isNew: boolean;
  sectionTitle: (title: string, icon?: React.ReactNode) => React.ReactNode;
}

export const OfferConfigurationTab: React.FC<OfferConfigurationTabProps> = ({
  offerName,
  setOfferName,
  offerType,
  setOfferType,
  resortId,
  handleResortChange,
  isActive,
  setIsActive,
  isCancellable,
  setIsCancellable,
  bookingStart,
  setBookingStart,
  bookingEnd,
  setBookingEnd,
  travelStart,
  setTravelStart,
  travelEnd,
  setTravelEnd,
  unitRows,
  updateUnitRow,
  availableToAdd,
  selectedUnitToAdd,
  setSelectedUnitToAdd,
  handleAddUnit,
  deleteUnitRow,
  inclusions,
  setInclusions,
  blockedAccountTypes,
  setBlockedAccountTypes,
  blockedAccountStatuses,
  setBlockedAccountStatuses,
  blockedClubs,
  setBlockedClubs,
  allowedUserTypes,
  setAllowedUserTypes,
  publishMode,
  setPublishMode,
  scheduledPublishAt,
  setScheduledPublishAt,
  publishedAt,
  rawConfig,
  setRawConfig,
  resorts,
  accountTypes,
  accountStatuses,
  clubs,
  canEdit,
  isNew,
  sectionTitle,
}) => {
  return (
    <Grid gutter="xl">
      {/* Left Column: Basics, Timeline, Units */}
      <Grid.Col span={{ base: 12, lg: 8 }}>
        <Stack gap="xl">
          {/* Section 1: Offer Basics */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("Section 1 — Offer Basics", <IconTag size={20} style={{ color: "#868e96" }} />)}
            <Stack gap="md">
              <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
                <TextInput
                  label="Offer Name"
                  placeholder="e.g. Summer Hot Deal 2026"
                  value={offerName}
                  onChange={(e) => setOfferName(e.currentTarget.value)}
                  required
                  readOnly={!canEdit}
                  styles={{ input: { fontWeight: 600 } }}
                  radius="md"
                />
                <Select
                  label="Offer Type"
                  description={!isNew ? "Offer type cannot be changed after creation" : undefined}
                  data={[
                    { value: "HOT_DEAL", label: "Hot Deal" },
                    { value: "EXCLUSIVE_DISCOVERY", label: "Exclusive Discovery" },
                  ]}
                  value={offerType}
                  onChange={(v) => { if (isNew && v) setOfferType(v as OfferType); }}
                  disabled={!isNew}
                  radius="md"
                />
              </SimpleGrid>

              <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
                <Select
                  label="Target Resort"
                  placeholder="Select resort"
                  data={resorts.map((r) => ({ value: r.id, label: r.name }))}
                  value={resortId}
                  onChange={handleResortChange}
                  disabled={!canEdit}
                  required
                  searchable
                  radius="md"
                />
                <Paper p="sm" radius="md" style={{ background: "#f8f9fa", border: "1px solid #e9ecef" }}>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Offer Status Controls</Text>
                  <Group gap="xl">
                    <Switch
                      label="Is Active & Bookable"
                      checked={isActive}
                      onChange={(e) => setIsActive(e.currentTarget.checked)}
                      disabled={!canEdit}
                      color="dark"
                    />
                    <Switch
                      label="Is Cancellable"
                      checked={isCancellable}
                      onChange={(e) => setIsCancellable(e.currentTarget.checked)}
                      disabled={!canEdit}
                      color="dark"
                    />
                  </Group>
                </Paper>
              </SimpleGrid>
            </Stack>
          </Paper>

          {/* Section 2: Booking & Travel Timeline */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("Section 2 — Booking & Travel Timeline", <IconCalendar size={20} style={{ color: "#868e96" }} />)}
            <Stack gap="lg">
              <SimpleGrid cols={{ base: 1, md: 2 }} spacing="xl">
                {/* Booking card */}
                <Paper withBorder p="md" radius="lg" style={{ background: "#f8f9fa", borderLeft: "4px solid #ced4da" }}>
                  <Group gap="xs" mb="md">
                    <ThemeIcon color="gray" size={24} radius="xl">
                      <IconCalendar size={14} />
                    </ThemeIcon>
                    <Text size="sm" fw={700} c="gray.8">BOOKING WINDOW</Text>
                  </Group>
                  <SimpleGrid cols={2} spacing="md">
                    <DateInput
                      label="Start Date"
                      placeholder="DD/MM/YYYY"
                      value={bookingStart ? new Date(bookingStart) : null}
                      onChange={(v) => setBookingStart(v ? moment(v).format("YYYY-MM-DD") : null)}
                      readOnly={!canEdit}
                      required
                      valueFormat="DD/MM/YYYY"
                      radius="md"
                    />
                    <DateInput
                      label="End Date"
                      placeholder="DD/MM/YYYY"
                      value={bookingEnd ? new Date(bookingEnd) : null}
                      onChange={(v) => setBookingEnd(v ? moment(v).format("YYYY-MM-DD") : null)}
                      readOnly={!canEdit}
                      required
                      valueFormat="DD/MM/YYYY"
                      radius="md"
                    />
                  </SimpleGrid>
                </Paper>

                {/* Travel card */}
                <Paper withBorder p="md" radius="lg" style={{ background: "#f8f9fa", borderLeft: "4px solid #ced4da" }}>
                  <Group gap="xs" mb="md">
                    <ThemeIcon color="gray" size={24} radius="xl">
                      <IconCalendar size={14} />
                    </ThemeIcon>
                    <Text size="sm" fw={700} c="gray.8">TRAVEL WINDOW</Text>
                  </Group>
                  <SimpleGrid cols={2} spacing="md">
                    <DateInput
                      label="Start Date"
                      placeholder="DD/MM/YYYY"
                      value={travelStart ? new Date(travelStart) : null}
                      onChange={(v) => setTravelStart(v ? moment(v).format("YYYY-MM-DD") : null)}
                      readOnly={!canEdit}
                      required
                      valueFormat="DD/MM/YYYY"
                      radius="md"
                    />
                    <DateInput
                      label="End Date"
                      placeholder="DD/MM/YYYY"
                      value={travelEnd ? new Date(travelEnd) : null}
                      onChange={(v) => setTravelEnd(v ? moment(v).format("YYYY-MM-DD") : null)}
                      readOnly={!canEdit}
                      required
                      valueFormat="DD/MM/YYYY"
                      radius="md"
                    />
                  </SimpleGrid>
                </Paper>
              </SimpleGrid>

              {/* Graphical visual representation of the timeline */}
              {(bookingStart || bookingEnd || travelStart || travelEnd) && (
                <Paper withBorder p="md" radius="lg" style={{ background: "#f8f9fa" }}>
                  <Text size="xs" fw={700} c="gray.7" mb="sm" style={{ textTransform: "uppercase", letterSpacing: "0.5px" }}>Visual Timeline Roadmap</Text>
                  <Group justify="space-between" align="center" wrap="nowrap" style={{ overflowX: "auto" }}>
                    {/* Booking Start Point */}
                    <Paper p="xs" radius="md" withBorder style={{ flex: 1, textAlign: "center", minWidth: 100, background: "#ffffff" }}>
                      <Text size="10px" fw={700} c="dimmed">BOOKING STARTS</Text>
                      <Text size="xs" fw={700} c="gray.7">{bookingStart ? moment(bookingStart).format("DD MMM YYYY") : "—"}</Text>
                    </Paper>

                    <Text size="xl" c="gray.4">→</Text>

                    {/* Booking End Point */}
                    <Paper p="xs" radius="md" withBorder style={{ flex: 1, textAlign: "center", minWidth: 100, background: "#ffffff" }}>
                      <Text size="10px" fw={700} c="dimmed">BOOKING ENDS</Text>
                      <Text size="xs" fw={700} c="gray.7">{bookingEnd ? moment(bookingEnd).format("DD MMM YYYY") : "—"}</Text>
                    </Paper>

                    <Text size="xl" c="gray.4">→</Text>

                    {/* Travel Start Point */}
                    <Paper p="xs" radius="md" withBorder style={{ flex: 1, textAlign: "center", minWidth: 100, background: "#ffffff" }}>
                      <Text size="10px" fw={700} c="dimmed">TRAVEL STARTS</Text>
                      <Text size="xs" fw={700} c="gray.7">{travelStart ? moment(travelStart).format("DD MMM YYYY") : "—"}</Text>
                    </Paper>

                    <Text size="xl" c="gray.4">→</Text>

                    {/* Travel End Point */}
                    <Paper p="xs" radius="md" withBorder style={{ flex: 1, textAlign: "center", minWidth: 100, background: "#ffffff" }}>
                      <Text size="10px" fw={700} c="dimmed">TRAVEL ENDS</Text>
                      <Text size="xs" fw={700} c="gray.7">{travelEnd ? moment(travelEnd).format("DD MMM YYYY") : "—"}</Text>
                    </Paper>
                  </Group>
                </Paper>
              )}

              {bookingEnd && travelStart && moment(bookingEnd).isAfter(moment(travelStart)) && (
                <Alert color="orange" icon={<IconAlertCircle size={16} />} radius="md">
                  Booking Period End is after Travel Period Start. This means members can still make bookings after their travel window begins.
                </Alert>
              )}
            </Stack>
          </Paper>

          {/* Section 3: Eligible Accommodations */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("Section 3 — Eligible Accommodations & Offer Values", <IconSettings size={20} style={{ color: "#868e96" }} />)}
            {!resortId ? (
              <Paper withBorder p="xl" radius="md" style={{ background: "#f8f9fa", textAlign: "center" }}>
                <Text size="sm" c="dimmed">Please select a resort in Section 1 to configure accommodation units.</Text>
              </Paper>
            ) : (
              <>
                {/* Add Accommodation Dropdown & Button */}
                {availableToAdd.length > 0 && canEdit && (
                  <Group gap="xs" mb="md" align="flex-end">
                    <Select
                      label="Add Accommodation Unit"
                      placeholder="Select unit to add"
                      data={availableToAdd.map((u) => ({ value: u.id, label: `${u.unit_name} (${u.unit_vp_code})` }))}
                      value={selectedUnitToAdd}
                      onChange={setSelectedUnitToAdd}
                      searchable
                      clearable
                      size="sm"
                      radius="md"
                      style={{ flex: 1, maxWidth: 350 }}
                    />
                    <Button
                      size="sm"
                      radius="md"
                      color="dark"
                      onClick={handleAddUnit}
                      disabled={!selectedUnitToAdd}
                    >
                      Add Unit
                    </Button>
                  </Group>
                )}

                {unitRows.length === 0 ? (
                  <Paper withBorder p="xl" radius="md" style={{ background: "#f8f9fa", textAlign: "center" }}>
                    <Text size="sm" c="dimmed">No accommodation units configured. Use the dropdown above to add one.</Text>
                  </Paper>
                ) : (
                  <Paper withBorder radius="md" style={{ overflow: "hidden", border: "1px solid #e9ecef" }}>
                    <Table verticalSpacing="sm" horizontalSpacing="md" highlightOnHover>
                      <Table.Thead style={{ background: "#f8f9fa" }}>
                        <Table.Tr>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 80 }}>Eligible</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057" }}>Unit Accommodation</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 100 }}>VP Code</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 150 }}>Value Type</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 110 }}>Value</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 110 }}>Min Nights</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 110 }}>Max Nights</Table.Th>
                          <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 110 }}>Max Units/Mbr</Table.Th>
                          {canEdit && <Table.Th style={{ fontSize: "11px", textTransform: "uppercase", color: "#495057", width: 60 }}>Action</Table.Th>}
                        </Table.Tr>
                      </Table.Thead>
                      <Table.Tbody>
                        {unitRows.map((row) => (
                          <Table.Tr
                            key={row.resort_unit_id}
                            style={{
                              backgroundColor: row.is_selected ? "#fafafa" : "transparent",
                              opacity: row.is_selected ? 1 : 0.6,
                              transition: "all 0.15s ease",
                            }}
                          >
                            <Table.Td>
                              <Checkbox
                                checked={row.is_selected}
                                onChange={(e) => updateUnitRow(row.resort_unit_id, "is_selected", e.currentTarget.checked)}
                                disabled={!canEdit}
                                styles={{ input: { cursor: !canEdit ? "not-allowed" : "pointer" } }}
                              />
                            </Table.Td>
                            <Table.Td>
                              <Text size="sm" fw={700} c={row.is_selected ? "gray.8" : "gray.6"}>
                                {row.unit_name}
                              </Text>
                              {row.unit_type && (
                                <Badge size="sm" color="gray" variant="light" mt={2}>
                                  {row.unit_type}
                                </Badge>
                              )}
                            </Table.Td>
                            <Table.Td>
                              <Text size="sm" style={{ fontFamily: "monospace", fontWeight: 600, color: "#495057" }}>
                                {row.unit_vp_code}
                              </Text>
                            </Table.Td>
                            <Table.Td>
                              <Select
                                data={[
                                  { value: "PERCENTAGE", label: "% Discount" },
                                  { value: "POINTS", label: "Points" },
                                ]}
                                value={row.offer_value_type}
                                onChange={(v) => updateUnitRow(row.resort_unit_id, "offer_value_type", v as any)}
                                disabled={!canEdit || !row.is_selected}
                                clearable
                                size="sm"
                                radius="md"
                                placeholder="Select type"
                              />
                            </Table.Td>
                            <Table.Td>
                              <NumberInput
                                value={row.offer_value}
                                onChange={(v) => updateUnitRow(row.resort_unit_id, "offer_value", v)}
                                readOnly={!canEdit || !row.is_selected}
                                size="sm"
                                radius="md"
                                min={0}
                                placeholder="—"
                              />
                            </Table.Td>
                            <Table.Td>
                              <NumberInput
                                value={row.minimum_nights}
                                onChange={(v) => updateUnitRow(row.resort_unit_id, "minimum_nights", v)}
                                readOnly={!canEdit || !row.is_selected}
                                size="sm"
                                radius="md"
                                min={0}
                                placeholder="—"
                              />
                            </Table.Td>
                            <Table.Td>
                              <NumberInput
                                value={row.maximum_nights_per_booking}
                                onChange={(v) => updateUnitRow(row.resort_unit_id, "maximum_nights_per_booking", v)}
                                readOnly={!canEdit || !row.is_selected}
                                size="sm"
                                radius="md"
                                min={0}
                                placeholder="—"
                              />
                            </Table.Td>
                            <Table.Td>
                              <NumberInput
                                value={row.maximum_units_per_membership}
                                onChange={(v) => updateUnitRow(row.resort_unit_id, "maximum_units_per_membership", v)}
                                readOnly={!canEdit || !row.is_selected}
                                size="sm"
                                radius="md"
                                min={0}
                                placeholder="—"
                              />
                            </Table.Td>
                            {canEdit && (
                              <Table.Td>
                                <Tooltip label="Remove from list">
                                  <Button
                                    variant="subtle"
                                    color="red"
                                    size="xs"
                                    p={4}
                                    onClick={() => deleteUnitRow(row.resort_unit_id)}
                                  >
                                    <IconTrash size={16} />
                                  </Button>
                                </Tooltip>
                              </Table.Td>
                            )}
                          </Table.Tr>
                        ))}
                      </Table.Tbody>
                    </Table>
                  </Paper>
                )}
              </>
            )}
          </Paper>

          {/* Inclusions Paper */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("What's Included (Inclusions)", <IconFileText size={20} style={{ color: "#868e96" }} />)}
            <Box>
              {canEdit ? (
                <RichTextComp content={inclusions} onChange={setInclusions} />
              ) : (
                <Paper withBorder p="sm" radius="md" style={{ background: "#f8f9fa" }}>
                  <div dangerouslySetInnerHTML={{ __html: inclusions || "<p>—</p>" }} />
                </Paper>
              )}
            </Box>
          </Paper>

          {offerType === "HOT_DEAL" && (
            <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
              {sectionTitle("Hot Deal Settings", <IconSettings size={20} style={{ color: "#868e96" }} />)}
              <Stack gap="lg">
                {/* Calculation */}
                <Box>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Points Calculation</Text>
                  <Stack gap="md">
                    <SimpleGrid cols={{ base: 1, sm: 3 }} spacing="md">
                      <Select
                        label="Calculation Mode"
                        value={rawConfig.calculation_mode ?? "phase-3"}
                        onChange={(v) => setRawConfig((prev) => ({ ...prev, calculation_mode: v }))}
                        data={[
                          { value: "phase-3", label: "phase-3" },
                          { value: "standard", label: "standard" },
                        ]}
                        disabled={!canEdit}
                        radius="md"
                      />
                      <NumberInput
                        label="Phase 3 Min Nights"
                        value={rawConfig.phase_3_min_night ?? 3}
                        onChange={(v) => setRawConfig((prev) => ({ ...prev, phase_3_min_night: v === "" ? undefined : Number(v) }))}
                        disabled={!canEdit}
                        radius="md"
                      />
                      <NumberInput
                        label="Phase 3 Max Nights"
                        value={rawConfig.phase_3_max_night ?? 7}
                        onChange={(v) => setRawConfig((prev) => ({ ...prev, phase_3_max_night: v === "" ? undefined : Number(v) }))}
                        disabled={!canEdit}
                        radius="md"
                      />
                    </SimpleGrid>
                    <Group>
                      <Checkbox
                        label="Allow Breakdown"
                        checked={rawConfig.allow_breakdown ?? false}
                        onChange={(e) => setRawConfig((prev) => ({ ...prev, allow_breakdown: e.currentTarget.checked }))}
                        disabled={!canEdit}
                      />
                      <Checkbox
                        label="Weekly"
                        checked={rawConfig.weekly ?? false}
                        onChange={(e) => setRawConfig((prev) => ({ ...prev, weekly: e.currentTarget.checked }))}
                        disabled={!canEdit}
                      />
                    </Group>
                  </Stack>
                </Box>

                {/* Capacity & pricing */}
                <Box>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Capacity & Pricing</Text>
                  <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
                    <NumberInput
                      label="Nights (night)"
                      description="Default stay length for this deal"
                      value={rawConfig.night ?? ""}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, night: v === "" ? undefined : Number(v) }))}
                      disabled={!canEdit}
                      radius="md"
                    />
                    <NumberInput
                      label="Occupancy up to (occ_up_to)"
                      value={rawConfig.occ_up_to ?? ""}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, occ_up_to: v === "" ? undefined : Number(v) }))}
                      disabled={!canEdit}
                      radius="md"
                    />
                    <NumberInput
                      label="Flat Price (price)"
                      description="Flat points price; 0 for percentage deals"
                      value={rawConfig.price ?? ""}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, price: v === "" ? undefined : Number(v) }))}
                      disabled={!canEdit}
                      radius="md"
                    />
                    <Select
                      label="Label By (label_by)"
                      value={rawConfig.label_by ?? null}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, label_by: v ?? undefined }))}
                      data={[
                        { value: "pay_hot_deal", label: "pay_hot_deal" },
                        { value: "exclusive_offer", label: "exclusive_offer" },
                      ]}
                      clearable
                      disabled={!canEdit}
                      radius="md"
                    />
                    <Select
                      label="Deal Type (type)"
                      description="Leave empty for standard hot deals"
                      value={rawConfig.type ?? null}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, type: v ?? undefined }))}
                      data={[{ value: "exclusive_offer", label: "exclusive_offer" }]}
                      clearable
                      disabled={!canEdit}
                      radius="md"
                    />
                  </SimpleGrid>
                </Box>

                {/* Nightly-deal date bounds */}
                <Box>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Nightly Deal Date Bounds</Text>
                  <Text size="xs" c="dimmed" mb="sm">
                    For open-ended nightly deals (e.g. Jimbaran / Kandara) that use min/max dates instead of a fixed travel range.
                    The deal's booking start/expiry come from the <b>Booking Window</b> in Section 2 above.
                  </Text>
                  <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
                    <DateInput
                      label="Min Date (min_date)"
                      value={rawConfig.min_date ? new Date(rawConfig.min_date) : null}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, min_date: v ? moment(v).format("YYYY-MM-DD") : undefined }))}
                      disabled={!canEdit}
                      clearable
                      valueFormat="DD MMM YYYY"
                      radius="md"
                    />
                    <DateInput
                      label="Max Date (max_date)"
                      value={rawConfig.max_date ? new Date(rawConfig.max_date) : null}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, max_date: v ? moment(v).format("YYYY-MM-DD") : undefined }))}
                      disabled={!canEdit}
                      clearable
                      valueFormat="DD MMM YYYY"
                      radius="md"
                    />
                  </SimpleGrid>
                  <Checkbox
                    mt="md"
                    label='Show "New" badge (new)'
                    checked={rawConfig.new === "new" || rawConfig.new === true}
                    onChange={(e) => setRawConfig((prev) => ({ ...prev, new: e.currentTarget.checked ? "new" : "" }))}
                    disabled={!canEdit}
                  />
                </Box>

                {/* Media */}
                <Box>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Media & Links</Text>
                  <Stack gap="md">
                    <TextInput
                      label="Thumbnail URL (thumbnail)"
                      value={rawConfig.thumbnail ?? ""}
                      onChange={(e) => setRawConfig((prev) => ({ ...prev, thumbnail: e.currentTarget.value || undefined }))}
                      disabled={!canEdit}
                      radius="md"
                    />
                    <TextInput
                      label="Destination Profile URL (destination_profile_url)"
                      value={rawConfig.destination_profile_url ?? ""}
                      onChange={(e) => setRawConfig((prev) => ({ ...prev, destination_profile_url: e.currentTarget.value || undefined }))}
                      disabled={!canEdit}
                      radius="md"
                    />
                  </Stack>
                </Box>

                {/* Inclusions cost */}
                <Box>
                  <Text size="xs" fw={700} c="gray.7" mb="xs" style={{ textTransform: "uppercase" }}>Inclusions Cost</Text>
                  <Group align="flex-end">
                    <NumberInput
                      label="Min nights for inclusions (inclusions_cost_min_nights)"
                      value={rawConfig.inclusions_cost_min_nights ?? ""}
                      onChange={(v) => setRawConfig((prev) => ({ ...prev, inclusions_cost_min_nights: v === "" ? undefined : Number(v) }))}
                      disabled={!canEdit}
                      radius="md"
                      w={320}
                    />
                    <Checkbox
                      label="Inclusions cost at bottom (inclusions_cost_bottom)"
                      checked={rawConfig.inclusions_cost_bottom ?? false}
                      onChange={(e) => setRawConfig((prev) => ({ ...prev, inclusions_cost_bottom: e.currentTarget.checked }))}
                      disabled={!canEdit}
                      mb={8}
                    />
                  </Group>
                </Box>

                {/* Roles */}
                <TextInput
                  label="Simple Roles (comma separated)"
                  description="e.g. type_krr, contract_kc_elite. Complex {and:[…]} conditions are preserved on save."
                  value={((rawConfig.roles ?? []) as string[]).filter((r: any) => typeof r === 'string').join(", ")}
                  onChange={(e) => {
                    const simple = e.currentTarget.value.split(",").map(s => s.trim()).filter(Boolean);
                    const complex = ((rawConfig.roles ?? []) as any[]).filter(r => typeof r !== 'string');
                    setRawConfig((prev) => ({ ...prev, roles: [...simple, ...complex] }));
                  }}
                  disabled={!canEdit}
                  radius="md"
                />
              </Stack>
            </Paper>
          )}
        </Stack>
      </Grid.Col>

      {/* Right Column: Publishing, Rules, Templates */}
      <Grid.Col span={{ base: 12, lg: 4 }}>
        <Stack gap="xl">
          {/* Section 7: Publishing Mode (SHIFTED TO TOP) */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("Publishing Settings", <IconSend size={20} style={{ color: "#868e96" }} />)}
            <Stack gap="md">
              <Text size="xs" fw={600} c="gray.7" style={{ textTransform: "uppercase" }}>Select Publish Mode</Text>

              <Stack gap="xs">
                {[
                  { value: "DRAFT", label: "Save as Draft", desc: "Keep hidden from members to continue editing later", color: "gray", icon: <IconEdit size={16} /> },
                  { value: "SCHEDULED", label: "Schedule Later", desc: "Automatically publish at a specified date/time", color: "gray", icon: <IconClock size={16} /> },
                  { value: "PUBLISHED", label: "Publish Now", desc: "Make active and visible immediately", color: "gray", icon: <IconCheck size={16} /> }
                ].map((opt) => {
                  const isSelected = publishMode === opt.value;
                  const isDisabled = !canEdit;
                  return (
                    <Paper
                      key={opt.value}
                      withBorder
                      p="sm"
                      radius="md"
                      onClick={() => { if (!isDisabled) setPublishMode(opt.value as any); }}
                      style={{
                        cursor: isDisabled ? "not-allowed" : "pointer",
                        opacity: isDisabled ? 0.6 : 1,
                        borderColor: isSelected ? `var(--mantine-color-${opt.color}-filled)` : "#e9ecef",
                        backgroundColor: isSelected ? `var(--mantine-color-${opt.color}-light)` : "#ffffff",
                        transition: "all 0.15s ease",
                      }}
                    >
                      <Group justify="space-between" wrap="nowrap" gap="xs">
                        <Group gap="xs">
                          <ThemeIcon size={24} radius="md" color={isSelected ? opt.color : "gray"} variant={isSelected ? "filled" : "light"}>
                            {opt.icon}
                          </ThemeIcon>
                          <Stack gap={1}>
                            <Text size="xs" fw={700} c={isSelected ? `${opt.color}.9` : "gray.8"}>
                              {opt.label}
                            </Text>
                            <Text size="10px" c="dimmed">
                              {opt.desc}
                            </Text>
                          </Stack>
                        </Group>
                        <Radio
                          checked={isSelected}
                          onChange={() => { }}
                          disabled={isDisabled}
                          color={opt.color}
                          styles={{ radio: { cursor: isDisabled ? "not-allowed" : "pointer" } }}
                        />
                      </Group>
                    </Paper>
                  );
                })}
              </Stack>

              {publishMode === "SCHEDULED" && (
                <DateTimePicker
                  label="Scheduled Publish Date & Time"
                  placeholder="Select date & time"
                  value={scheduledPublishAt ? new Date(scheduledPublishAt) : null}
                  onChange={(v: any) => setScheduledPublishAt(v ? (v instanceof Date ? v.toISOString() : new Date(v).toISOString()) : null)}
                  readOnly={!canEdit}
                  required
                  radius="md"
                  valueFormat="DD/MM/YYYY HH:mm"
                />
              )}

              {!isNew && publishedAt && (
                <Paper p="xs" radius="md" style={{ background: "#f8f9fa", border: "1px solid #e9ecef" }}>
                  <Text size="xs" c="dimmed" style={{ textAlign: "center" }}>
                    Published at: <strong style={{ color: "#495057" }}>{moment(publishedAt).format("DD MMM YYYY, HH:mm")}</strong>
                  </Text>
                </Paper>
              )}
            </Stack>
          </Paper>

          {/* Section 4: Eligibility Rules */}
          <Paper withBorder radius="lg" p="lg" style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.01)", background: "#ffffff" }}>
            {sectionTitle("Eligibility Rules", <IconLock size={20} style={{ color: "#868e96" }} />)}
            <Stack gap="md">
              <MultiSelect
                label="Blocked Account Types"
                description="Members with these account types cannot book"
                data={accountTypes.map((t) => ({ value: t.id, label: t.label }))}
                value={blockedAccountTypes}
                onChange={setBlockedAccountTypes}
                disabled={!canEdit}
                clearable
                searchable
                radius="md"
              />
              <MultiSelect
                label="Blocked Account Statuses"
                data={accountStatuses.map((t) => ({ value: t.id, label: t.label }))}
                value={blockedAccountStatuses}
                onChange={setBlockedAccountStatuses}
                disabled={!canEdit}
                clearable
                searchable
                radius="md"
              />
              <MultiSelect
                label="Blocked Clubs"
                data={clubs.map((c) => ({ value: c.id, label: c.label }))}
                value={blockedClubs}
                onChange={setBlockedClubs}
                disabled={!canEdit}
                clearable
                searchable
                radius="md"
              />

              <Box mt="xs" style={{ width: "100%" }}>
                <Text size="sm" fw={600} mb={2}>Allowed User Types</Text>
                <Text size="xs" c="dimmed" mb="md">Uncheck to restrict who can reserve bookings under this offer</Text>
                <SimpleGrid cols={1} spacing="xs">
                  {(["LEGAL_OWNER", "FAMILY_MEMBER", "GUEST"] as AllowedUserType[]).map((ut) => {
                    const isSelected = allowedUserTypes.includes(ut);
                    const label = ut.replace("_", " ").charAt(0) + ut.replace("_", " ").slice(1).toLowerCase();
                    const isDisabled = !canEdit;
                    return (
                      <Paper
                        key={ut}
                        withBorder
                        px="sm"
                        py="xs"
                        radius="md"
                        onClick={() => {
                          if (isDisabled) return;
                          if (isSelected) {
                            setAllowedUserTypes((prev) => prev.filter((x) => x !== ut));
                          } else {
                            setAllowedUserTypes((prev) => [...prev, ut]);
                          }
                        }}
                        style={{
                          cursor: isDisabled ? "not-allowed" : "pointer",
                          opacity: isDisabled ? 0.6 : 1,
                          borderColor: isSelected ? "#343a40" : "#e9ecef",
                          backgroundColor: isSelected ? "#f8f9fa" : "#ffffff",
                          transition: "all 0.15s ease",
                        }}
                      >
                        <Group justify="space-between" wrap="nowrap">
                          <Group gap="xs">
                            <ThemeIcon size={20} radius="xl" color={isSelected ? "dark" : "gray"} variant={isSelected ? "filled" : "light"}>
                              <IconCheck size={10} />
                            </ThemeIcon>
                            <Text size="xs" fw={700} c={isSelected ? "dark" : "gray.7"}>
                              {label}
                            </Text>
                          </Group>
                          <Checkbox
                            checked={isSelected}
                            onChange={() => { }}
                            disabled={isDisabled}
                            color="dark"
                            styles={{ input: { pointerEvents: "none" } }}
                          />
                        </Group>
                      </Paper>
                    );
                  })}
                </SimpleGrid>
              </Box>
            </Stack>
          </Paper>
        </Stack>
      </Grid.Col>
    </Grid>
  );
};
