"use client";

import {
  ActionIcon,
  Alert,
  Badge,
  Button,
  Checkbox,
  Container,
  Divider,
  Grid,
  Group,
  Modal,
  NumberInput,
  Paper,
  Select,
  Stack,
  Switch,
  Table,
  Text,
  Textarea,
  TextInput,
  Title,
} from "@mantine/core";
import { DateInput } from "@mantine/dates";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import {
  IconAlertCircle,
  IconArrowLeft,
  IconBuilding,
  IconDeviceFloppy,
  IconHistory,
  IconPlus,
  IconTrash,
  IconClock,
} from "@tabler/icons-react";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { createResort, updateResort, deleteResort } from "@/lib/features/resorts/action";
import { RichTextComp } from "@/components/Richtext";
import type {
  Resort,
  ResortUnit,
  DateRangeEntry,
  OpenClosePeriod,
  ResortSeason,
  ResortGrade,
} from "@/lib/features/resorts/types";
import type { AccessScope } from "@/lib/features/types";
import { ResortsLogsPanel } from "../_components/ResortsLogsPanel";
import { useRoleAccess } from "@/hooks/useRoleAccess";
import { ResortGeneralPanel } from "../_components/ResortGeneralPanel";
import { ResortPeriodsPanel } from "../_components/ResortPeriodsPanel";
import { ResortInventoryPanel } from "../_components/ResortInventoryPanel";
import { WorkflowSidebar } from "@/components/WorkflowSidebar";
import { getWorkflowTaskByEntity } from "@/lib/features/workflow/query";

interface Props {
  initialResort: Resort | null;
  isNew: boolean;
  initialError?: string;
  accessScope: AccessScope;
  unitTypes: string[];
}

const INITIAL_SEASONS: ResortSeason[] = [
  { season_colour: "RED", date_ranges: [] },
  { season_colour: "WHITE", date_ranges: [] },
  { season_colour: "BLUE", date_ranges: [] },
];

const SEASON_BADGE_COLORS: Record<string, string> = {
  RED: "red",
  WHITE: "gray",
  BLUE: "blue",
};

function newDateRange(): DateRangeEntry {
  return { id: crypto.randomUUID(), label: "", start_date: "", end_date: "" };
}

function newOpenClosePeriod(): OpenClosePeriod {
  return { id: crypto.randomUUID(), label: "", period_type: "ONE_OFF", start_date: "", end_date: "" };
}

function newUnit(): ResortUnit {
  return {
    id: crypto.randomUUID(),
    resort_id: "",
    unit_name: "",
    unit_vp_code: "",
    unit_type: "",
    total_occupancy: undefined as any,
    adult_occupancy: undefined as any,
    children_occupancy: undefined as any,
    child_occupancy: undefined as any,
    is_active: true,
    eligible_for_hot_deals: true,
    eligible_for_exclusive_discovery: true,
    sort_order: 0,
    description: "",
    featured_image: "",
    images: [],
    created_at: "",
    updated_at: "",
  };
}

export default function ResortEditorClientPage({
  initialResort,
  isNew,
  initialError,
  accessScope,
  unitTypes,
}: Props) {
  const navigate = useNavigate();
  const { checkClientAccess } = useRoleAccess();
  const canViewAdminLogs = checkClientAccess("read", "admin-logs");

  const r = initialResort;

  const [name, setName] = useState(r?.name ?? "");
  const [code, setCode] = useState(r?.code ?? "");
  const [description, setDescription] = useState(r?.description ?? "");
  const [address, setAddress] = useState(r?.address ?? "");
  const [country, setCountry] = useState(r?.country ?? "");
  const [stateRegion, setStateRegion] = useState(r?.state_region ?? "");
  const [phone, setPhone] = useState(r?.phone ?? "");
  const [email, setEmail] = useState(r?.email ?? "");
  const [websiteUrl, setWebsiteUrl] = useState(r?.website_url ?? "");
  const [grade, setGrade] = useState<ResortGrade | null>((r?.grade as ResortGrade) ?? null);
  const [isActive, setIsActive] = useState(r?.is_active ?? true);

  const [coverImage, setCoverImage] = useState(r?.cover_image ?? "");
  const [thumbnail, setThumbnail] = useState(r?.thumbnail ?? "");
  const [mapImage, setMapImage] = useState(r?.map_image ?? "");
  const [mobileBanner, setMobileBanner] = useState(r?.mobile_banner ?? "");
  const [resortLogo, setResortLogo] = useState(r?.resort_logo ?? "");
  const [galleryImages, setGalleryImages] = useState<string[]>(r?.gallery_images ?? []);




  const [adultAgeFrom, setAdultAgeFrom] = useState<number | "">(r?.adult_age_from ?? "");
  const [adultAgeTo, setAdultAgeTo] = useState<number | "">(r?.adult_age_to ?? "");
  const [childrenAgeFrom, setChildrenAgeFrom] = useState<number | "">(r?.children_age_from ?? "");
  const [childrenAgeTo, setChildrenAgeTo] = useState<number | "">(r?.children_age_to ?? "");
  const [infantAgeFrom, setInfantAgeFrom] = useState<number | "">(r?.infant_age_from ?? "");
  const [infantAgeTo, setInfantAgeTo] = useState<number | "">(r?.infant_age_to ?? "");

  const [units, setUnits] = useState<ResortUnit[]>(r?.units ?? []);
  const [peakPeriods, setPeakPeriods] = useState<DateRangeEntry[]>(r?.peak_periods ?? []);
  const [blackoutPeriods, setBlackoutPeriods] = useState<DateRangeEntry[]>(r?.blackout_periods ?? []);
  const [openClosePeriods, setOpenClosePeriods] = useState<OpenClosePeriod[]>(r?.open_close_periods ?? []);
  const [seasons, setSeasons] = useState<ResortSeason[]>(
    r?.seasons?.length ? r.seasons : INITIAL_SEASONS,
  );

  const [saving, setSaving] = useState(false);
  const [deleteOpened, { open: openDelete, close: closeDelete }] = useDisclosure(false);
  const [deleting, setDeleting] = useState(false);
  const [logsOpened, { open: openLogs, close: closeLogs }] = useDisclosure(false);
  const [workflowOpened, { open: openWorkflow, close: closeWorkflow }] = useDisclosure(false);
  const [workflowStatus, setWorkflowStatus] = useState<string | null>(null);

  useEffect(() => {
    if (!isNew && r?.id) {
      getWorkflowTaskByEntity("RESORT", r.id)
        .then((res) => {
          if (res.success && res.data) {
            setWorkflowStatus(res.data.status);
          }
        })
        .catch(() => {});
    }
  }, [isNew, r?.id]);

  const canEdit = isNew ? accessScope.create : accessScope.update;

  const buildPayload = () => ({
    name: name.trim(),
    code: code.trim() || undefined,
    description: description || undefined,
    address: address.trim() || undefined,
    country: country.trim() || undefined,
    state_region: stateRegion.trim() || undefined,
    phone: phone.trim() || undefined,
    email: email.trim() || undefined,
    website_url: websiteUrl.trim() || undefined,
    cover_image: coverImage.trim() || undefined,
    thumbnail: thumbnail.trim() || undefined,
    map_image: mapImage.trim() || undefined,
    mobile_banner: mobileBanner.trim() || undefined,
    resort_logo: resortLogo.trim() || undefined,
    gallery_images: galleryImages,
    grade: grade ?? undefined,
    is_active: isActive,
    adult_age_from: adultAgeFrom !== "" ? Number(adultAgeFrom) : null,
    adult_age_to: adultAgeTo !== "" ? Number(adultAgeTo) : null,
    children_age_from: childrenAgeFrom !== "" ? Number(childrenAgeFrom) : null,
    children_age_to: childrenAgeTo !== "" ? Number(childrenAgeTo) : null,
    infant_age_from: infantAgeFrom !== "" ? Number(infantAgeFrom) : null,
    infant_age_to: infantAgeTo !== "" ? Number(infantAgeTo) : null,
    units: units.map((u, idx) => ({ ...u, sort_order: idx })),
    peak_periods: peakPeriods,
    blackout_periods: blackoutPeriods,
    open_close_periods: openClosePeriods,
    seasons,
  });

  const handleSave = async () => {
    if (!name.trim()) {
      notifications.show({ color: "red", message: "Resort name is required" });
      return;
    }
    setSaving(true);
    try {
      const payload = buildPayload();
      const res = isNew
        ? await createResort(payload as any)
        : await updateResort(r!.id, payload as any);
      if (res.success && res.data) {
        notifications.show({ color: "green", message: isNew ? "Resort created" : "Resort saved" });
        if (isNew) navigate(`/admin/resorts/${res.data.id}`);
      } else {
        notifications.show({ color: "red", message: res.message || "Save failed" });
      }
    } catch {
      notifications.show({ color: "red", message: "Save failed" });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!r) return;
    setDeleting(true);
    try {
      const res = await deleteResort(r.id);
      if (res.success) {
        notifications.show({ color: "green", message: "Resort deleted" });
        navigate("/admin/resorts");
      } else {
        notifications.show({ color: "red", message: res.message || "Delete failed" });
      }
    } catch {
      notifications.show({ color: "red", message: "Delete failed" });
    } finally {
      setDeleting(false);
    }
  };

  // ── Section helpers ──────────────────────────────────────────────────────────

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

  const updateDateRange = (
    setter: React.Dispatch<React.SetStateAction<DateRangeEntry[]>>,
    id: string,
    field: keyof DateRangeEntry,
    val: any,
  ) => setter((prev) => prev.map((d) => (d.id === id ? { ...d, [field]: val } : d)));

  const removeDateRange = (
    setter: React.Dispatch<React.SetStateAction<DateRangeEntry[]>>,
    id: string,
  ) => setter((prev) => prev.filter((d) => d.id !== id));

  const updateOpenClose = (id: string, field: keyof OpenClosePeriod, val: any) =>
    setOpenClosePeriods((prev) => prev.map((p) => (p.id === id ? { ...p, [field]: val } : p)));

  const updateSeasonRange = (colour: string, id: string, field: keyof DateRangeEntry, val: any) =>
    setSeasons((prev) =>
      prev.map((s) =>
        s.season_colour === colour
          ? { ...s, date_ranges: s.date_ranges.map((d) => (d.id === id ? { ...d, [field]: val } : d)) }
          : s,
      ),
    );

  const removeSeasonRange = (colour: string, id: string) =>
    setSeasons((prev) =>
      prev.map((s) =>
        s.season_colour === colour
          ? { ...s, date_ranges: s.date_ranges.filter((d) => d.id !== id) }
          : s,
      ),
    );

  const addSeasonRange = (colour: string) =>
    setSeasons((prev) =>
      prev.map((s) =>
        s.season_colour === colour ? { ...s, date_ranges: [...s.date_ranges, newDateRange()] } : s,
      ),
    );

  const sectionTitle = (title: string) => (
    <>
      <Title order={5} mb="xs" style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>{title}</Title>
      <Divider mb="md" />
    </>
  );

  return (
    <Container fluid px="xl" py="xl">
      {/* Header */}
      <Group justify="space-between" mb="lg">
        <Group gap="sm">
          <Button variant="subtle" size="compact-sm" leftSection={<IconArrowLeft size={14} />} onClick={() => navigate(-1)} style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 600 }}>
            Back
          </Button>
          <IconBuilding size={24} />
          <Title order={2} style={{ fontFamily: "Outfit, Inter, sans-serif", fontWeight: 700 }}>{isNew ? "New Resort" : (name || "Resort")}</Title>
          {!isNew && (
            <Badge color={isActive ? "green" : "gray"} variant="light">
              {isActive ? "Active" : "Inactive"}
            </Badge>
          )}
          {!isNew && workflowStatus && (
            <Badge
              color={
                workflowStatus === "VERIFIED"
                  ? "green"
                  : workflowStatus === "CHANGE_REQUESTED"
                  ? "red"
                  : workflowStatus === "READY_FOR_REVIEW"
                  ? "blue"
                  : workflowStatus === "CONTENT_IN_PROGRESS"
                  ? "yellow"
                  : workflowStatus === "READY_FOR_CONTENT"
                  ? "cyan"
                  : "gray"
              }
              variant="filled"
            >
              {workflowStatus.replace(/_/g, " ")}
            </Badge>
          )}
        </Group>
        <Group>
          {!isNew && (
            <Button variant="light" color="blue" leftSection={<IconClock size={16} />} onClick={openWorkflow}>
              Workflow
            </Button>
          )}
          {!isNew && accessScope.delete && (
            <Button variant="subtle" color="red" leftSection={<IconTrash size={16} />} onClick={openDelete}>
              Delete
            </Button>
          )}
          {!isNew && canViewAdminLogs && (
            <Button variant="light" color="gray" leftSection={<IconHistory size={16} />} onClick={openLogs}>
              Activity
            </Button>
          )}
          {canEdit && (
            <Button leftSection={<IconDeviceFloppy size={16} />} onClick={handleSave} loading={saving}>
              {isNew ? "Create Resort" : "Save Changes"}
            </Button>
          )}
        </Group>
      </Group>

      {initialError && (
        <Alert color="red" icon={<IconAlertCircle size={16} />} mb="lg">{initialError}</Alert>
      )}

      <Grid gutter="xl">
        <Grid.Col span={{ base: 12, lg: 8 }}>
          <ResortGeneralPanel
            name={name}
            setName={setName}
            code={code}
            setCode={setCode}
            description={description}
            setDescription={setDescription}
            grade={grade}
            setGrade={setGrade}
            isActive={isActive}
            setIsActive={setIsActive}
            adultAgeFrom={adultAgeFrom}
            setAdultAgeFrom={setAdultAgeFrom}
            adultAgeTo={adultAgeTo}
            setAdultAgeTo={setAdultAgeTo}
            childrenAgeFrom={childrenAgeFrom}
            setChildrenAgeFrom={setChildrenAgeFrom}
            childrenAgeTo={childrenAgeTo}
            setChildrenAgeTo={setChildrenAgeTo}
            infantAgeFrom={infantAgeFrom}
            setInfantAgeFrom={setInfantAgeFrom}
            infantAgeTo={infantAgeTo}
            setInfantAgeTo={setInfantAgeTo}
            canEdit={canEdit}
            sectionTitle={sectionTitle}
          />
        </Grid.Col>

        <Grid.Col span={{ base: 12, lg: 4 }}>
          <ResortPeriodsPanel
            peakPeriods={peakPeriods}
            setPeakPeriods={setPeakPeriods}
            blackoutPeriods={blackoutPeriods}
            setBlackoutPeriods={setBlackoutPeriods}
            openClosePeriods={openClosePeriods}
            setOpenClosePeriods={setOpenClosePeriods}
            canEdit={canEdit}
            sectionTitle={sectionTitle}
          />
        </Grid.Col>

        {/* SECTION 4 — Resort Inventory & Accommodations (Full-Width) */}
        <Grid.Col span={12}>
          <ResortInventoryPanel
            units={units}
            setUnits={setUnits}
            unitTypes={unitTypes}
            canEdit={canEdit}
            sectionTitle={sectionTitle}
          />
        </Grid.Col>
      </Grid>

      {/* Delete modal */}
      <Modal opened={deleteOpened} onClose={closeDelete} title="Delete Resort" centered size="sm">
        <Stack>
          <Text size="sm">
            Are you sure you want to delete{" "}
            <Text span fw={700}>{r?.name}</Text>?
            This will permanently delete the resort and all its units and bookings data.
          </Text>
          <Group justify="flex-end">
            <Button variant="subtle" onClick={closeDelete}>Cancel</Button>
            <Button color="red" onClick={handleDelete} loading={deleting}>Delete</Button>
          </Group>
        </Stack>
      </Modal>

      {/* Logs modal */}
      {canViewAdminLogs && (
        <Modal opened={logsOpened} onClose={closeLogs} title="Resort Activity" size="lg" centered>
          <ResortsLogsPanel resortId={r?.id ?? null} />
        </Modal>
      )}

      {/* Workflow drawer */}
      {!isNew && r?.id && (
        <WorkflowSidebar
          opened={workflowOpened}
          onClose={closeWorkflow}
          entityType="RESORT"
          entityId={r.id}
          onWorkflowUpdated={(newStatus) => setWorkflowStatus(newStatus)}
        />
      )}


    </Container>
  );
}
