import { TextInput, Flex, Box, Button } from "@mantine/core";
import { CalendarIcon } from "@phosphor-icons/react";
import { useSheet } from "@/hooks/use-sheet";
import Sheet from "@/components/sheet/sheet";
import { DateTimePicker } from "../features/admin/components/date-time-picker";

interface DateInputProps {
  label: string;
  value: string;
  onChange: (value: string) => void;
  withAsterisk?: boolean;
  error?: React.ReactNode;
  placeholder?: string;
}

// Date input that opens a sheet with mantine date time picker when clicked
export const DateInputSheet = ({ 
  label, 
  value, 
  onChange, 
  withAsterisk, 
  error,
  placeholder 
}: DateInputProps) => {
  const sheet = useSheet();

  const formatDisplayValue = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '';
    return date.toLocaleDateString('en-US', {
      weekday: 'short',
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true
    });
  };

  const handleDateChange = (newValue: string | null) => {
    onChange(newValue || '');
    sheet.close();
  };

  const dateValue = value ? new Date(value) : null;

  return (
    <>
      <TextInput
        label={label}
        value={formatDisplayValue(value)}
        onClick={sheet.open}
        readOnly
        withAsterisk={withAsterisk}
        error={error}
        placeholder={placeholder || "Click to select date"}
        rightSection={<CalendarIcon size={16} />}
        style={{ cursor: 'pointer' }}
      />
      
      <Sheet {...sheet.props} title={`Select ${label}`}>
        <Flex gap='xs' direction='column' justify='center' p="md">
          <Box mx='auto'>
            <DateTimePicker
              value={dateValue}
              onChange={handleDateChange}
            />
          </Box>
          <Button onClick={sheet.close} variant="subtle">
            Close
          </Button>
        </Flex>
      </Sheet>
    </>
  );
};