import React, { useState, useEffect } from 'react';
import { DatePicker } from '@mantine/dates';
import { useHotkeys } from '@mantine/hooks';
import { IconCalendarEvent, IconCheck } from '@tabler/icons-react';
import { Button, Checkbox, Grid, Group, Popover, Text, TextInput, Tooltip } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import dayjs from 'dayjs';
import { translate } from '../../utils/i18n';
import { formatDate, dbdateFormate, dueDateFieldStyles } from '../../utils/dateFormatting';

/**
 * Shared due date picker UI component.
 * Contains all visual state and calendar logic; delegates save/clear to the parent via callbacks.
 *
 * Props:
 *   dueDate              — current due date string (or null)
 *   startDate            — current start date string (or null)
 *   startDateIsVisible   — whether start date checkbox should be checked initially
 *   dueDateIsVisible     — whether due date checkbox should be checked initially
 *   disabled             — blocks the popover and grays out the trigger
 *   showStartDateInPill  — show "startDate to dueDate" in the pill (pass true for drawers/card view)
 *   withinPortal         — pass true when DatePicker needs to render outside its scroll container
 *   singleDateStartOffset — 0 (default) or -1; controls start date when range mode is off
 *   onSave(dateData)     — called with { dates:[start,end], visibility:{...} } on Save
 *   onClear()            — called on Clear
 *   isSaving             — show loader on Save button (owned by parent)
 *   isClearing           — show loader on Clear button (owned by parent)
 */
const DueDatePicker = ({
  dueDate,
  startDate,
  startDateIsVisible,
  dueDateIsVisible,
  disabled = false,
  showStartDateInPill = false,
  withinPortal = false,
  singleDateStartOffset = 0,
  onSave,
  onClear,
  isSaving = false,
  isClearing = false,
}) => {
  const [selectedDates, setSelectedDates] = useState([]);
  const [calendarVisible, setCalendarVisible] = useState(false);
  const [startDateDefaultCheck, setStartDateDefaultCheck] = useState(startDateIsVisible || false);
  const [dueDateDefaultCheck, setDueDateDefaultCheck] = useState(true);

  const current = dueDate ? new Date(dueDate) : new Date();
  let defaultStart = new Date();
  defaultStart.setDate(defaultStart.getDate() - 1);
  if (startDate) {
    defaultStart = new Date(startDate);
  }

  const [selectedValue, setSelectedValue] = useState([defaultStart, current]);

  useEffect(() => {
    if (dueDate) {
      setSelectedDates([new Date(dueDate)]);
      const s = startDate ? new Date(startDate) : new Date(new Date().setDate(new Date().getDate() - 1));
      setSelectedValue([s, new Date(dueDate)]);
    }
  }, [dueDate]);

  useHotkeys([['Escape', () => setCalendarVisible(false)]]);

  const isOverdue = (date) => {
    const today = new Date();
    const due = new Date(date);
    return due < today.setHours(0, 0, 0, 0);
  };

  const handlerDateChange = (value) => {
    if (!dueDateDefaultCheck) {
      notifications.show({
        color: 'red',
        title: translate('Please enable due date to select date.'),
        icon: <IconCheck />,
        autoClose: 5000,
      });
      return;
    }
    if (value) {
      if (startDateDefaultCheck) {
        setSelectedValue(value);
      } else {
        const endDate = new Date(value);
        const start = new Date(endDate);
        start.setDate(start.getDate() + singleDateStartOffset);
        setSelectedValue([start, endDate]);
      }
    }
  };

  const applyQuickDate = (date) => {
    const endDate = new Date(date);
    const start = new Date(endDate);
    start.setDate(start.getDate() + singleDateStartOffset);
    setSelectedValue([start, endDate]);
  };

  const handlerStartDateDefaultCheck = () => {
    if (selectedValue) {
      const s = new Date(selectedValue[0]);
      const e = selectedValue[1] ? new Date(selectedValue[1]) : new Date(s);
      if (s.getDate() === e.getDate()) s.setDate(e.getDate() - 1);
      setSelectedValue([s, e]);
    } else {
      setSelectedValue([defaultStart, current]);
    }
    setStartDateDefaultCheck((prev) => !prev);
  };

  const handlerEndDateDefaultCheck = () => {
    if (selectedValue) {
      const s = selectedValue[0] ? new Date(selectedValue[0]) : new Date();
      const e = selectedValue[1] ? new Date(selectedValue[1]) : new Date(s);
      if (s.getDate() === e.getDate()) s.setDate(e.getDate() - 1);
      setSelectedValue([s, e]);
    } else {
      setSelectedValue([defaultStart, current]);
    }
    setDueDateDefaultCheck((prev) => !prev);
  };

  const handleSave = async () => {
    if (!selectedValue || !selectedValue[0] || !selectedValue[1]) return;
    const dateData = {
      dates: startDateDefaultCheck ? selectedValue : [selectedValue[1], selectedValue[1]],
      visibility: {
        startDateIsVisible: startDateDefaultCheck,
        dueDateIsVisible: dueDateDefaultCheck,
      },
    };
    const result = await onSave(dateData);
    const ok = result?.payload?.status === 200 || result?.status === 200 || result === true;
    if (ok) setCalendarVisible(false);
  };

  const handleClear = () => {
    onClear();
    // Reset local visual state immediately so the pill updates
    setSelectedDates([]);
    setSelectedValue([null, null]);
    setStartDateDefaultCheck(false);
    setDueDateDefaultCheck(true);
    setCalendarVisible(false);
  };

  const handleOpen = () => {
    if (!disabled) setCalendarVisible((prev) => !prev);
  };

  // Close popover when parent finishes saving
  useEffect(() => {
    if (!isSaving && !isClearing) {
      // Intentionally not auto-closing here — wrappers call setCalendarVisible via onSave success
    }
  }, [isSaving, isClearing]);

  return (
    <div className="due-select-btn">
      <Popover
        opened={calendarVisible}
        onChange={setCalendarVisible}
        width={310}
        position="bottom"
        shadow={false}
        offset={6}
        closeOnEscape
        closeOnClickOutside
        onClose={() => setCalendarVisible(false)}
        disabled={disabled}
      >
        <Popover.Target>
          <Tooltip label={translate('Due Date')} position="top" withArrow>
            {selectedDates.length > 0 ? (
              <div
                onClick={handleOpen}
                className={`due-selected h-[28px] px-3 py-0 rounded-full border flex items-center gap-1.5 transition-colors ${disabled ? 'opacity-50 cursor-not-allowed' : `cursor-pointer ${isOverdue(selectedDates[0]) ? 'hover:bg-red-100' : 'hover:bg-gray-50'}`} ${isOverdue(selectedDates[0]) ? 'border-red-200 bg-red-50' : 'border-gray-200 bg-white'}`}
              >
                <IconCalendarEvent size={16} className={isOverdue(selectedDates[0]) ? 'text-red-500' : 'text-gray-500'} stroke={1.5} />
                <span className={`text-[12px] font-medium leading-none whitespace-nowrap ${isOverdue(selectedDates[0]) ? 'text-red-600' : 'text-gray-700'}`}>
                  {showStartDateInPill && startDate && startDateIsVisible && (
                    <span className="font-normal">{dbdateFormate(startDate)} to </span>
                  )}
                  {formatDate(selectedDates[0])}
                </span>
              </div>
            ) : (
              dueDate === null ? (
                <div
                  onClick={handleOpen}
                  className={`flex items-center justify-center h-[28px] w-[28px] border border-dashed border-gray-300 rounded-full transition-colors bg-white ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-gray-50'}`}
                >
                  <IconCalendarEvent color="#9CA3AF" size={16} stroke={1.5} />
                </div>
              ) : (
                <div
                  onClick={handleOpen}
                  className={`due-selected h-[28px] px-3 py-0 rounded-full border border-gray-200 bg-white flex items-center gap-1.5 transition-colors ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-gray-50'}`}
                >
                  <IconCalendarEvent size={16} className="text-gray-500" stroke={1.5} />
                  <span className="text-gray-700 font-medium text-[12px] leading-none whitespace-nowrap">
                    {dbdateFormate(dueDate)}
                  </span>
                </div>
              )
            )}
          </Tooltip>
        </Popover.Target>

        <Popover.Dropdown style={{
          padding: 0,
          border: '1px solid #E2E8F0',
          borderRadius: '12px',
          boxShadow: '0 8px 32px rgba(0,0,0,.12)',
          overflow: 'hidden',
        }}>
          {/* Header */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 16px 10px', borderBottom: '1px solid #E2E8F0',
          }}>
            <span style={{ fontSize: '13px', fontWeight: 700, color: '#1A202C', display: 'flex', alignItems: 'center', gap: '6px' }}>
              <IconCalendarEvent size={13} stroke={1.5} color="#39758D" />
              {translate('Set Due Date')}
            </span>
          </div>

          {/* Quick shortcuts */}
          <div style={{ display: 'flex', gap: '6px', padding: '10px 16px 0' }}>
            {[
              { label: translate('Today'),     getValue: () => new Date() },
              { label: translate('Tomorrow'),  getValue: () => { const d = new Date(); d.setDate(d.getDate() + 1); return d; } },
              { label: translate('Next Week'), getValue: () => { const d = new Date(); d.setDate(d.getDate() + 7); return d; } },
            ].map(({ label, getValue }) => (
              <button key={label} type="button" onClick={() => applyQuickDate(getValue())}
                style={{ fontSize: '11px', fontWeight: 600, color: '#39758D', background: '#EBF1F4',
                  border: 'none', borderRadius: '9999px', padding: '3px 10px', cursor: 'pointer', fontFamily: 'inherit' }}>
                {label}
              </button>
            ))}
          </div>

          {/* Body */}
          <div style={{ padding: '10px 16px 14px' }}>
            <DatePicker
              withinPortal={withinPortal}
              size="sm"
              type={startDateDefaultCheck ? 'range' : 'single'}
              value={
                dueDateDefaultCheck
                  ? (startDateDefaultCheck ? selectedValue : (selectedValue && selectedValue[1]))
                  : ['', '']
              }
              onChange={handlerDateChange}
            />

            <Group justify="flex-start" spacing="xs" className="mt-[12px] mb-[6px] w-full">
              <Checkbox
                label={translate('Use Date Range')}
                labelPosition="left"
                onChange={handlerStartDateDefaultCheck}
                checked={startDateDefaultCheck}
                size="sm"
                styles={{ label: { fontWeight: 'bold', color: '#202020' } }}
              />
            </Group>

            {startDateDefaultCheck && (
              <>
                <div className="h-[1px] bg-gray-200 w-full mb-[8px]"></div>
                <Grid className="my-1">
                  <Grid.Col span={6}>
                    <Grid gap={1} align="center">
                      <Grid.Col span={12}>
                        <Text c="#64748B" size="xs" fw={700} style={{ textTransform: 'uppercase', letterSpacing: '0.5px' }}>{translate('Start Date')}</Text>
                      </Grid.Col>
                      <Grid.Col className="!p-0" span="auto">
                        <TextInput
                          size="xs"
                          placeholder="DD-MM-YYYY"
                          disabled={!startDateDefaultCheck}
                          value={startDateDefaultCheck && selectedValue && selectedValue[0] ? dbdateFormate(selectedValue[0]) : ''}
                          ml={6}
                          styles={dueDateFieldStyles}
                        />
                      </Grid.Col>
                    </Grid>
                  </Grid.Col>
                  <Grid.Col span={6}>
                    <Grid gap={1} align="center">
                      <Grid.Col span={12}>
                        <Text c="#64748B" size="xs" fw={700} style={{ textTransform: 'uppercase', letterSpacing: '0.5px' }}>{translate('Due Date')}</Text>
                      </Grid.Col>
                      <Grid.Col className="!p-0" span="auto">
                        <TextInput
                          size="xs"
                          placeholder="DD-MM-YYYY"
                          disabled={!dueDateDefaultCheck}
                          value={dueDateDefaultCheck && selectedValue && selectedValue[1] ? dbdateFormate(selectedValue[1]) : ''}
                          styles={dueDateFieldStyles}
                        />
                      </Grid.Col>
                    </Grid>
                  </Grid.Col>
                </Grid>
              </>
            )}
          </div>

          {/* Footer */}
          <div style={{
            padding: '10px 16px 14px',
            display: 'flex',
            justifyContent: 'space-between',
            borderTop: '1px solid #E2E8F0',
          }}>
            <Button
              onClick={handleClear}
              size="xs"
              variant="subtle"
              color="gray"
              radius="md"
              loading={isClearing}
              loaderProps={{ type: 'dots' }}
              disabled={isClearing}
              className="px-4"
            >
              {translate('Clear')}
            </Button>
            <Button
              onClick={handleSave}
              size="xs"
              variant="filled"
              color="#39758D"
              radius="md"
              loading={isSaving}
              loaderProps={{ type: 'dots' }}
              disabled={isSaving}
              className="px-6"
            >
              {translate('Save')}
            </Button>
          </div>
        </Popover.Dropdown>
      </Popover>
    </div>
  );
};

export default DueDatePicker;
