import * as React from 'react';
import { useState } from 'react';
import {
  ChevronLeft,
  ChevronRight,
  Calendar as CalendarIcon,
} from 'lucide-react';
import { Button } from '@/figma-make/components/base/button';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/figma-make/components/base/popover';
import { Input } from '@/figma-make/components/base/input';

interface DateRangePickerProps {
  dateFrom: string;
  dateTo: string;
  onDateChange: (from: string, to: string) => void;
  disabled?: boolean;
}

const PRESET_OPTIONS = [
  { label: 'Last 7 days', value: 'last_7_days' },
  { label: 'Last 14 Days', value: 'last_14_days' },
  { label: 'Last 30 Days', value: 'last_30_days' },
  { label: 'Last 3 months', value: 'last_3_months' },
  { label: 'Last 12 months', value: 'last_12_months' },
  { label: 'Month to date', value: 'month_to_date' },
  { label: 'Quarter to date', value: 'quarter_to_date' },
  { label: 'All time', value: 'all_time' },
  { label: 'Custom', value: 'custom' },
];

export function DateRangePicker({
  dateFrom,
  dateTo,
  onDateChange,
  disabled = false,
}: DateRangePickerProps) {
  const [open, setOpen] = useState(false);
  const [selectedPreset, setSelectedPreset] = useState('custom');
  const [tempDateFrom, setTempDateFrom] = useState(dateFrom);
  const [tempDateTo, setTempDateTo] = useState(dateTo);
  const [currentMonth1, setCurrentMonth1] = useState(() => {
    const date = dateFrom ? new Date(dateFrom) : new Date();
    return { year: date.getFullYear(), month: date.getMonth() };
  });
  const [currentMonth2, setCurrentMonth2] = useState(() => {
    const date = dateFrom ? new Date(dateFrom) : new Date();
    const nextMonth = new Date(date.getFullYear(), date.getMonth() + 1);
    return { year: nextMonth.getFullYear(), month: nextMonth.getMonth() };
  });

  const formatDateDisplay = (dateStr: string) => {
    if (!dateStr) return 'Select date';
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
  };

  const handlePresetClick = (preset: string) => {
    setSelectedPreset(preset);
    const today = new Date();
    let from = '';
    let to = today.toISOString().split('T')[0];

    switch (preset) {
      case 'last_7_days':
        from = new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000)
          .toISOString()
          .split('T')[0];
        break;
      case 'last_14_days':
        from = new Date(today.getTime() - 13 * 24 * 60 * 60 * 1000)
          .toISOString()
          .split('T')[0];
        break;
      case 'last_30_days':
        from = new Date(today.getTime() - 29 * 24 * 60 * 60 * 1000)
          .toISOString()
          .split('T')[0];
        break;
      case 'last_3_months':
        from = new Date(
          today.getFullYear(),
          today.getMonth() - 3,
          today.getDate()
        )
          .toISOString()
          .split('T')[0];
        break;
      case 'last_12_months':
        from = new Date(
          today.getFullYear(),
          today.getMonth() - 12,
          today.getDate()
        )
          .toISOString()
          .split('T')[0];
        break;
      case 'month_to_date':
        from = new Date(today.getFullYear(), today.getMonth(), 1)
          .toISOString()
          .split('T')[0];
        break;
      case 'quarter_to_date':
        const quarter = Math.floor(today.getMonth() / 3);
        from = new Date(today.getFullYear(), quarter * 3, 1)
          .toISOString()
          .split('T')[0];
        break;
      case 'all_time':
        from = '2020-01-01';
        break;
      case 'custom':
        from = tempDateFrom;
        to = tempDateTo;
        break;
    }

    setTempDateFrom(from);
    setTempDateTo(to);
  };

  const handleSetDate = () => {
    onDateChange(tempDateFrom, tempDateTo);
    setOpen(false);
  };

  const handleCancel = () => {
    setTempDateFrom(dateFrom);
    setTempDateTo(dateTo);
    setOpen(false);
  };

  const navigateMonth = (direction: 'prev' | 'next', calendar: 1 | 2) => {
    if (calendar === 1) {
      const newDate = new Date(
        currentMonth1.year,
        currentMonth1.month + (direction === 'next' ? 1 : -1)
      );
      setCurrentMonth1({
        year: newDate.getFullYear(),
        month: newDate.getMonth(),
      });
    } else {
      const newDate = new Date(
        currentMonth2.year,
        currentMonth2.month + (direction === 'next' ? 1 : -1)
      );
      setCurrentMonth2({
        year: newDate.getFullYear(),
        month: newDate.getMonth(),
      });
    }
  };

  const renderCalendar = (
    year: number,
    month: number,
    onNavigate: (dir: 'prev' | 'next') => void
  ) => {
    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const monthName = new Date(year, month).toLocaleDateString('en-US', {
      month: 'long',
    });

    const days = [];
    for (let i = 0; i < firstDay; i++) {
      days.push(<div key={`empty-${i}`} className='h-9 w-9' />);
    }

    for (let day = 1; day <= daysInMonth; day++) {
      const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      const isInRange =
        tempDateFrom &&
        tempDateTo &&
        dateStr >= tempDateFrom &&
        dateStr <= tempDateTo;
      const isStart = dateStr === tempDateFrom;
      const isEnd = dateStr === tempDateTo;
      const isToday = dateStr === new Date().toISOString().split('T')[0];

      days.push(
        <button
          key={day}
          onClick={() => {
            if (selectedPreset !== 'custom') {
              setSelectedPreset('custom');
            }
            if (!tempDateFrom || (tempDateFrom && tempDateTo)) {
              setTempDateFrom(dateStr);
              setTempDateTo('');
            } else {
              if (dateStr < tempDateFrom) {
                setTempDateTo(tempDateFrom);
                setTempDateFrom(dateStr);
              } else {
                setTempDateTo(dateStr);
              }
            }
          }}
          className={`
            h-9 w-9 rounded-md text-sm font-medium transition-colors
            ${isStart || isEnd ? 'bg-[#0069e0] text-white hover:bg-[#0052b3]' : ''}
            ${isInRange && !isStart && !isEnd ? 'bg-blue-50 text-blue-900' : ''}
            ${!isInRange && !isStart && !isEnd ? 'hover:bg-gray-100 text-gray-700' : ''}
            ${isToday && !isStart && !isEnd && !isInRange ? 'border border-[#0069e0]' : ''}
          `}
        >
          {day}
        </button>
      );
    }

    return (
      <div className='p-3'>
        <div className='flex items-center justify-between mb-3'>
          <button
            onClick={() => onNavigate('prev')}
            className='p-1 hover:bg-gray-100 rounded-md transition-colors'
          >
            <ChevronLeft className='w-4 h-4 text-gray-600' />
          </button>
          <div className='font-semibold text-sm text-gray-900'>
            {monthName} {year}
          </div>
          <button
            onClick={() => onNavigate('next')}
            className='p-1 hover:bg-gray-100 rounded-md transition-colors'
          >
            <ChevronRight className='w-4 h-4 text-gray-600' />
          </button>
        </div>
        <div className='grid grid-cols-7 gap-1 mb-2'>
          {['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map((day) => (
            <div
              key={day}
              className='h-9 w-9 flex items-center justify-center text-xs font-medium text-gray-500'
            >
              {day}
            </div>
          ))}
        </div>
        <div className='grid grid-cols-7 gap-1'>{days}</div>
      </div>
    );
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant='outline'
          disabled={disabled}
          className='justify-start text-left font-normal border-gray-200 hover:bg-gray-50'
        >
          <CalendarIcon className='mr-2 h-4 w-4 text-gray-500' />
          {dateFrom && dateTo ? (
            <span className='text-gray-900'>
              {formatDateDisplay(dateFrom)} → {formatDateDisplay(dateTo)}
            </span>
          ) : (
            <span className='text-gray-500'>Select date range</span>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className='w-auto p-0 bg-white shadow-lg rounded-xl'
        align='start'
      >
        <div className='flex'>
          {/* Preset Sidebar */}
          <div className='w-40 border-r border-gray-200 p-3 bg-gray-50'>
            {PRESET_OPTIONS.map((preset) => (
              <button
                key={preset.value}
                onClick={() => handlePresetClick(preset.value)}
                className={`
                  w-full text-left px-3 py-2 rounded-md text-sm transition-colors mb-1
                  ${
                    selectedPreset === preset.value
                      ? 'bg-blue-50 text-blue-900 font-medium'
                      : 'text-gray-700 hover:bg-gray-100'
                  }
                `}
              >
                {preset.label}
              </button>
            ))}
          </div>

          {/* Calendar Section */}
          <div>
            <div className='flex'>
              {renderCalendar(currentMonth1.year, currentMonth1.month, (dir) =>
                navigateMonth(dir, 1)
              )}
              {renderCalendar(currentMonth2.year, currentMonth2.month, (dir) =>
                navigateMonth(dir, 2)
              )}
            </div>

            {/* Date Input & Actions */}
            <div className='border-t border-gray-200 p-4 flex items-center justify-between gap-3'>
              <div className='flex items-center gap-2'>
                <Input
                  type='text'
                  value={formatDateDisplay(tempDateFrom)}
                  readOnly
                  className='w-28 text-sm text-center border-gray-200'
                />
                <span className='text-gray-400'>→</span>
                <Input
                  type='text'
                  value={formatDateDisplay(tempDateTo)}
                  readOnly
                  className='w-28 text-sm text-center border-gray-200'
                />
              </div>
              <div className='flex gap-2'>
                <Button
                  variant='outline'
                  onClick={handleCancel}
                  className='border-gray-200'
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleSetDate}
                  className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
                >
                  Set Date
                </Button>
              </div>
            </div>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}
