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

interface GuestFormProps {
  unitIndex: number;
  control: Control<CreateBookingFormData>;
  errors: FieldErrors<CreateBookingFormData>;
  setValue: any;
  watch: any;
}
const GuestForm: React.FC<GuestFormProps> = ({
  unitIndex,
  control,
  errors,
  setValue,
  watch,
}) => {
  const {
    fields: guestFields,
    append: appendGuest,
    remove: removeGuest,
  } = useFieldArray({
    control,
    name: `units.${unitIndex}.guests`,
  });

  const GUEST_TYPES = [
    { value: "OWNER", label: "Owner" },
    { value: "FAMILY", label: "Family" },
  ];

  const handleAddGuest = () => {
    appendGuest({
      contactID: "",
      isPrimaryGuest: guestFields.length === 0,
      type: "OWNER",
      sendBookingConfirmation: true,
      additional_data: {
        special_requests: "NA",
        has_travel_insurance: "true",
        is_pet_travelling: "false",
        medical_mobility_requirements: "None",
      },
    });
  };

  return (
    <div>
      <Group justify="space-between" mb="sm">
        <div>
          <Text fw={500}>Guests</Text>
          <Text size="sm" c="dimmed">
            Add guest details
          </Text>
        </div>
        <Button
          size="sm"
          variant="light"
          leftSection={<IconPlus size={16} />}
          onClick={handleAddGuest}
        >
          Add Guest
        </Button>
      </Group>

      <Stack gap="sm">
        {guestFields.map((guest, guestIndex) => (
          <Card key={guest.id} p="md" radius="md" withBorder>
            <Stack gap="md">
              <Group justify="space-between">
                <Text fw={500} size="sm">
                  Guest {guestIndex + 1}
                </Text>
                {guestFields.length > 0 && (
                  <ActionIcon
                    color="red"
                    variant="subtle"
                    size="sm"
                    onClick={() => removeGuest(guestIndex)}
                  >
                    <IconTrash size={16} />
                  </ActionIcon>
                )}
              </Group>

              <Grid>
                <Grid.Col span={{ base: 12, sm: 6 }}>
                  <Controller
                    name={`units.${unitIndex}.guests.${guestIndex}.contactID`}
                    control={control}
                    rules={{
                      required: "Contact ID is required",
                    }}
                    render={({ field }) => (
                      <TextInput
                        {...field}
                        label="Contact ID"
                        placeholder="e.g., 79265"
                        error={
                          errors.units?.[unitIndex]?.guests?.[guestIndex]
                            ?.contactID?.message
                        }
                        required
                      />
                    )}
                  />
                </Grid.Col>
              </Grid>

              <Grid>
                <Grid.Col span={{ base: 12, sm: 6 }}>
                  <Controller
                    name={`units.${unitIndex}.guests.${guestIndex}.type`}
                    control={control}
                    rules={{
                      required: "Guest type is required",
                    }}
                    render={({ field }) => (
                      <Select
                        {...field}
                        label="Guest Type"
                        placeholder="Select guest type"
                        data={GUEST_TYPES}
                        error={
                          (
                            errors.units?.[unitIndex]?.guests?.[guestIndex]
                              ?.type as FieldError
                          )?.message
                        }
                        required
                      />
                    )}
                  />
                </Grid.Col>
              </Grid>

              <Grid>
                <Grid.Col span={{ base: 12, sm: 6 }}>
                  <Controller
                    name={`units.${unitIndex}.guests.${guestIndex}.isPrimaryGuest`}
                    control={control}
                    render={({ field: { value, onChange } }) => (
                      <Checkbox
                        label="Primary Guest"
                        checked={value}
                        onChange={(e) => {
                          const checked = e.currentTarget.checked;
                          if (checked) {
                            const guests =
                              watch(`units.${unitIndex}.guests`) || [];
                            guests.forEach((_: any, idx: number) => {
                              setValue(
                                `units.${unitIndex}.guests.${idx}.isPrimaryGuest`,
                                idx === guestIndex,
                              );
                            });
                          } else {
                            onChange(false);
                          }
                        }}
                      />
                    )}
                  />
                </Grid.Col>
                <Grid.Col span={{ base: 12, sm: 6 }}>
                  <Controller
                    name={`units.${unitIndex}.guests.${guestIndex}.sendBookingConfirmation`}
                    control={control}
                    render={({ field: { value, onChange } }) => (
                      <Checkbox
                        label="Send Booking Confirmation"
                        checked={value}
                        onChange={(e) => onChange(e.currentTarget.checked)}
                      />
                    )}
                  />
                </Grid.Col>
              </Grid>

              <div>
                <Text fw={500} size="sm" mb="xs">
                  Additional Information
                </Text>
                <Grid>
                  <Grid.Col span={{ base: 12, sm: 6 }}>
                    <Controller
                      name={`units.${unitIndex}.guests.${guestIndex}.additional_data.special_requests`}
                      control={control}
                      render={({ field }) => (
                        <TextInput
                          {...field}
                          label="Special Requests"
                          placeholder="NA"
                        />
                      )}
                    />
                  </Grid.Col>

                  <Grid.Col span={{ base: 12, sm: 6 }}>
                    <Controller
                      name={`units.${unitIndex}.guests.${guestIndex}.additional_data.has_travel_insurance`}
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          label="Travel Insurance"
                          data={[
                            { value: "true", label: "Yes" },
                            { value: "false", label: "No" },
                          ]}
                        />
                      )}
                    />
                  </Grid.Col>
                </Grid>

                <Grid mt="sm">
                  <Grid.Col span={{ base: 12, sm: 6 }}>
                    <Controller
                      name={`units.${unitIndex}.guests.${guestIndex}.additional_data.is_pet_travelling`}
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          label="Pet Travelling"
                          data={[
                            { value: "true", label: "Yes" },
                            { value: "false", label: "No" },
                          ]}
                        />
                      )}
                    />
                  </Grid.Col>

                  <Grid.Col span={{ base: 12, sm: 6 }}>
                    <Controller
                      name={`units.${unitIndex}.guests.${guestIndex}.additional_data.medical_mobility_requirements`}
                      control={control}
                      render={({ field }) => (
                        <TextInput
                          {...field}
                          label="Medical/Mobility Requirements"
                          placeholder="None"
                        />
                      )}
                    />
                  </Grid.Col>
                </Grid>
              </div>
            </Stack>
          </Card>
        ))}

        {guestFields.length === 0 && (
          <Text size="sm" c="dimmed" ta="center" py="md">
            No guests added. Click "Add Guest" to add guest details.
          </Text>
        )}
      </Stack>
    </div>
  );
};

export default GuestForm;
