// React Imports
import React from 'react'

// MUI Imports
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { useTheme } from '@mui/material/styles'
import type { TextFieldProps } from '@mui/material/TextField'

interface DateRangePickerProps {
  /**
   * Start date value (Date object or date string)
   */
  startDate: Date | string | null
  /**
   * End date value (Date object or date string)
   */
  endDate: Date | string | null
  /**
   * Callback when start date changes
   */
  onStartDateChange: (date: Date | null) => void
  /**
   * Callback when end date changes
   */
  onEndDateChange: (date: Date | null) => void
  /**
   * Label for start date field
   */
  startLabel?: string
  /**
   * Label for end date field
   */
  endLabel?: string
  /**
   * Placeholder for start date field
   */
  startPlaceholder?: string
  /**
   * Placeholder for end date field
   */
  endPlaceholder?: string
  /**
   * Size of the text fields
   */
  size?: 'small' | 'medium'
  /**
   * Whether the fields are disabled
   */
  disabled?: boolean
  /**
   * Whether the fields are required
   */
  required?: boolean
  /**
   * Custom className for the container
   */
  className?: string
  /**
   * Custom styles for the container
   */
  containerStyle?: React.CSSProperties
  /**
   * Separator between date fields
   */
  separator?: string
  /**
   * Custom props for start date TextField
   */
  startTextFieldProps?: Omit<TextFieldProps, 'type' | 'value' | 'onChange'>
  /**
   * Custom props for end date TextField
   */
  endTextFieldProps?: Omit<TextFieldProps, 'type' | 'value' | 'onChange'>
  /**
   * Error state for start date
   */
  startError?: boolean
  /**
   * Error state for end date
   */
  endError?: boolean
  /**
   * Helper text for start date
   */
  startHelperText?: string
  /**
   * Helper text for end date
   */
  endHelperText?: string
}

// Utility functions
const formatDateForInput = (date: Date | string | null): string => {
  if (!date) return ''

  const dateObj = typeof date === 'string' ? new Date(date) : date

  if (isNaN(dateObj.getTime())) return ''

  return dateObj.toISOString().split('T')[0]
}

const parseDateFromInput = (dateString: string): Date | null => {
  if (!dateString) return null

  const date = new Date(dateString)
  return isNaN(date.getTime()) ? null : date
}

const DateRangePicker: React.FC<DateRangePickerProps> = ({
  startDate,
  endDate,
  onStartDateChange,
  onEndDateChange,
  startLabel,
  endLabel,
  startPlaceholder,
  endPlaceholder,
  size = 'small',
  disabled = false,
  required = false,
  className = '',
  containerStyle = {},
  separator = '-',
  startTextFieldProps = {},
  endTextFieldProps = {},
  startError = false,
  endError = false,
  startHelperText,
  endHelperText
}) => {
  const theme = useTheme()

  const defaultTextFieldSx = {
    '& .MuiOutlinedInput-root': {
      '&.Mui-focused fieldset': {
        borderColor: 'primary.main'
      },
      '& fieldset': {
        borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
      }
    }
  }

  const handleStartDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const date = parseDateFromInput(event.target.value)
    onStartDateChange(date)
  }

  const handleEndDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const date = parseDateFromInput(event.target.value)
    onEndDateChange(date)
  }

  return (
    <div className={`flex items-center gap-4 ${className}`} style={containerStyle}>
      <TextField
        type='date'
        label={startLabel}
        placeholder={startPlaceholder}
        value={formatDateForInput(startDate)}
        onChange={handleStartDateChange}
        size={size}
        disabled={disabled}
        required={required}
        error={startError}
        helperText={startHelperText}
        sx={{
          ...defaultTextFieldSx,
          ...startTextFieldProps.sx
        }}
        {...startTextFieldProps}
      />

      <Typography
        color='text.secondary'
        sx={{
          userSelect: 'none',
          fontSize: size === 'small' ? '14px' : '16px'
        }}
      >
        {separator}
      </Typography>

      <TextField
        type='date'
        label={endLabel}
        placeholder={endPlaceholder}
        value={formatDateForInput(endDate)}
        onChange={handleEndDateChange}
        size={size}
        disabled={disabled}
        required={required}
        error={endError}
        helperText={endHelperText}
        sx={{
          ...defaultTextFieldSx,
          ...endTextFieldProps.sx
        }}
        {...endTextFieldProps}
      />
    </div>
  )
}

export default DateRangePicker

// Export utility functions for external use
export { formatDateForInput, parseDateFromInput }

// Example usage:
/*
import DateRangePicker from '@/components/DateRangePicker'

// In your component:
const [startDate, setStartDate] = useState<Date | null>(new Date())
const [endDate, setEndDate] = useState<Date | null>(new Date())

// Basic usage
<DateRangePicker
  startDate={startDate}
  endDate={endDate}
  onStartDateChange={setStartDate}
  onEndDateChange={setEndDate}
/>

// With labels and validation
<DateRangePicker
  startDate={startDate}
  endDate={endDate}
  onStartDateChange={setStartDate}
  onEndDateChange={setEndDate}
  startLabel="Tanggal Mulai"
  endLabel="Tanggal Selesai"
  required
  startError={startDate && endDate && startDate > endDate}
  endError={startDate && endDate && startDate > endDate}
  startHelperText={startDate && endDate && startDate > endDate ? "Tanggal mulai tidak boleh lebih besar dari tanggal selesai" : ""}
/>

// Custom styling
<DateRangePicker
  startDate={startDate}
  endDate={endDate}
  onStartDateChange={setStartDate}
  onEndDateChange={setEndDate}
  separator="sampai"
  size="medium"
  className="my-custom-class"
  startTextFieldProps={{
    variant: "filled",
    sx: { minWidth: '150px' }
  }}
  endTextFieldProps={{
    variant: "filled", 
    sx: { minWidth: '150px' }
  }}
/>

// Integration with your existing filter logic
const handleDateRangeChange = (start: Date | null, end: Date | null) => {
  setFilter({
    ...filter,
    date_from: start ? formatDateDDMMYYYY(start) : null,
    date_to: end ? formatDateDDMMYYYY(end) : null
  })
}

<DateRangePicker
  startDate={filter.date_from ? new Date(filter.date_from) : null}
  endDate={filter.date_to ? new Date(filter.date_to) : null}
  onStartDateChange={(date) => handleDateRangeChange(date, filter.date_to ? new Date(filter.date_to) : null)}
  onEndDateChange={(date) => handleDateRangeChange(filter.date_from ? new Date(filter.date_from) : null, date)}
/>
*/
