import {
  TextInput,
  Select,
  Stack,
  Grid,
  Text,
  Button,
  Group,
  Textarea,
  NumberInput,
  Accordion,
  ActionIcon,
} from "@mantine/core";
import {
  Controller,
  type Control,
  type FieldErrors,
  useFieldArray,
} from "react-hook-form";
import { DEFAULT_UNIT_CHARGES, type CreateBookingFormData } from "@/lib/features/bookings/createBooking.types";
import { IconTrash, IconPlus } from "@tabler/icons-react";
import GuestForm from "./guestForm";
import ChargesForm from "./chargesForm";

interface UnitSectionProps {
  control: Control<CreateBookingFormData>;
  errors: FieldErrors<CreateBookingFormData>;
  watch: any;
  setValue: any;
}

const UnitSection: React.FC<UnitSectionProps> = ({
  control,
  errors,
  watch,
  setValue,
}) => {
  const {
    fields: unitFields,
    append: appendUnit,
    remove: removeUnit,
  } = useFieldArray({
    control,
    name: "units",
  });

  const BEDROOM_TYPES = [
    { value: "Hotel", label: "Hotel" },
    { value: "Studio", label: "Studio" },
    { value: "1 Bedroom", label: "1 Bedroom" },
    { value: "2 Bedroom", label: "2 Bedroom" },
    { value: "3 Bedroom", label: "3 Bedroom" },
    { value: "4 Bedroom", label: "4 Bedroom" },
  ];

  const handleAddUnit = () => {
    appendUnit({
      bedroom_type: "1 Bedroom",
      note: "",
      additionalData: {},
      guests: [
        {
          contactID: "",
          isPrimaryGuest: true,
          type: "OWNER",
          sendBookingConfirmation: true,
          additional_data: {
            special_requests: "NA",
            has_travel_insurance: "true",
            is_pet_travelling: "false",
            medical_mobility_requirements: "None",
          },
        },
      ],
      adults: 0,
      children: 0,
      infants: 0,
      externalBooking: {
        refID: "",
        additionalData: { channel: "RCI" },
      },
      checkInDate: "",
      checkOutDate: "",
      charges: DEFAULT_UNIT_CHARGES.map((charge) => ({ ...charge })),
    });
  };

  return (
    <Stack gap="md">
      <Group justify="space-between">
        <div>
          <Text fw={600}>Units</Text>
          <Text size="sm" c="dimmed">
            Add unit details and guest information
          </Text>
        </div>
        <Button leftSection={<IconPlus size={18} />} onClick={handleAddUnit}>
          Add Unit
        </Button>
      </Group>

      <Accordion>
        {unitFields.map((unit, unitIndex) => (
          <Accordion.Item key={unit.id} value={`unit-${unitIndex}`}>
            <Accordion.Control onClick={(e) => {}}>
              <Group
                justify="space-between"
                onClick={(e) => e.stopPropagation()}
              >
                <Text fw={500}>
                  Unit {unitIndex + 1} -{" "}
                  {watch(`units.${unitIndex}.bedroom_type`) || "Select Type"}
                </Text>
                {unitFields.length > 1 && (
                  <ActionIcon
                    color="red"
                    variant="subtle"
                    onClick={(e) => {
                      e.stopPropagation();
                      removeUnit(unitIndex);
                    }}
                  >
                    <IconTrash size={18} />
                  </ActionIcon>
                )}
              </Group>
            </Accordion.Control>
            <Accordion.Panel>
              <Stack gap="md">
                {/* Basic Unit Info */}
                <div>
                  <Text fw={500} mb="sm">
                    Basic Information
                  </Text>
                  <Grid>
                    <Grid.Col span={{ base: 12, sm: 6 }}>
                      <Controller
                        name={`units.${unitIndex}.bedroom_type`}
                        control={control}
                        rules={{ required: "Bedroom type is required" }}
                        render={({ field }) => (
                          <Select
                            {...field}
                            label="Bedroom Type"
                            placeholder="Select bedroom type"
                            data={BEDROOM_TYPES}
                            error={
                              errors.units?.[unitIndex]?.bedroom_type?.message
                            }
                            required
                          />
                        )}
                      />
                    </Grid.Col>

                    <Grid.Col span={{ base: 12, sm: 6 }}>
                      <Controller
                        name={`units.${unitIndex}.externalBooking.refID`}
                        control={control}
                        render={({ field }) => (
                          <TextInput
                            {...field}
                            label="External Booking Ref ID"
                            placeholder="e.g., AFFE0001000721"
                          />
                        )}
                      />
                    </Grid.Col>
                  </Grid>

                  <Grid mt="sm">
                    <Grid.Col span={12}>
                      <Controller
                        name={`units.${unitIndex}.note`}
                        control={control}
                        render={({ field }) => (
                          <Textarea
                            {...field}
                            label="Unit Notes"
                            placeholder="Enter any notes"
                            rows={2}
                          />
                        )}
                      />
                    </Grid.Col>
                  </Grid>
                </div>

                {/* Guest Information */}
                <div>
                  <Text fw={500} mb="sm">
                    Guest Information
                  </Text>
                  <Grid>
                    <Grid.Col span={{ base: 12, sm: 4 }}>
                      <Controller
                        name={`units.${unitIndex}.adults`}
                        control={control}
                        rules={{
                          required: "Adults count is required",
                          min: { value: 0, message: "Must be 0 or more" },
                        }}
                        render={({ field }) => (
                          <NumberInput
                            {...field}
                            label="Adults"
                            placeholder="0"
                            min={0}
                            error={errors.units?.[unitIndex]?.adults?.message}
                            required
                          />
                        )}
                      />
                    </Grid.Col>

                    <Grid.Col span={{ base: 12, sm: 4 }}>
                      <Controller
                        name={`units.${unitIndex}.children`}
                        control={control}
                        rules={{
                          required: "Children count is required",
                          min: { value: 0, message: "Must be 0 or more" },
                        }}
                        render={({ field }) => (
                          <NumberInput
                            {...field}
                            label="Children"
                            placeholder="0"
                            min={0}
                            error={errors.units?.[unitIndex]?.children?.message}
                            required
                          />
                        )}
                      />
                    </Grid.Col>

                    <Grid.Col span={{ base: 12, sm: 4 }}>
                      <Controller
                        name={`units.${unitIndex}.infants`}
                        control={control}
                        rules={{
                          required: "Infants count is required",
                          min: { value: 0, message: "Must be 0 or more" },
                        }}
                        render={({ field }) => (
                          <NumberInput
                            {...field}
                            label="Infants"
                            placeholder="0"
                            min={0}
                            error={errors.units?.[unitIndex]?.infants?.message}
                            required
                          />
                        )}
                      />
                    </Grid.Col>
                  </Grid>
                </div>

                {/* Dates */}
                <div>
                  <Text fw={500} mb="sm">
                    Stay Dates
                  </Text>
                  <Grid>
                    <Grid.Col span={{ base: 12, sm: 6 }}>
                      <Controller
                        name={`units.${unitIndex}.checkInDate`}
                        control={control}
                        rules={{ required: "Check-in date is required" }}
                        render={({ field }) => (
                          <TextInput
                            {...field}
                            type="date"
                            label="Check-In Date"
                            error={
                              errors.units?.[unitIndex]?.checkInDate?.message
                            }
                            required
                          />
                        )}
                      />
                    </Grid.Col>

                    <Grid.Col span={{ base: 12, sm: 6 }}>
                      <Controller
                        name={`units.${unitIndex}.checkOutDate`}
                        control={control}
                        rules={{ required: "Check-out date is required" }}
                        render={({ field }) => (
                          <TextInput
                            {...field}
                            type="date"
                            label="Check-Out Date"
                            error={
                              errors.units?.[unitIndex]?.checkOutDate?.message
                            }
                            required
                          />
                        )}
                      />
                    </Grid.Col>
                  </Grid>
                </div>

                {/* Guests */}
                <GuestForm
                  unitIndex={unitIndex}
                  control={control}
                  errors={errors}
                  watch={watch}
                  setValue={setValue}
                />

                {/* Charges */}
                <ChargesForm
                  unitIndex={unitIndex}
                  control={control}
                  errors={errors}
                />
              </Stack>
            </Accordion.Panel>
          </Accordion.Item>
        ))}
      </Accordion>
    </Stack>
  );
};

export default UnitSection;
