'use client';

import { useState, useCallback, useMemo } from 'react';
import { DayPicker, DayButtonProps } from 'react-day-picker';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { UsageEntry, UserPreferences, setUsageForDateAsync, clearDayDataAsync } from '@/lib/storage';
import { ChevronLeftIcon, ChevronRightIcon, Cigarette, Leaf, Sparkles } from 'lucide-react';
import { useTheme } from '@/lib/theme-context';
import { getLocalDateString, getTodayString } from '@/lib/date-utils';
import { DailyInspirationCard } from './DailyInspirationCard';
import { cn } from '@/lib/utils';
import React from 'react';


interface UsageCalendarProps {
  usageData: UsageEntry[];
  onDataUpdate: () => void;
  userId: string;
  religion?: 'christian' | 'secular' | null;
  onReligionUpdate?: (religion: 'christian' | 'secular') => void;
  preferences?: UserPreferences | null;
  onPreferencesUpdate?: (prefs: UserPreferences) => Promise<void>;
}

function UsageCalendarComponent({ usageData, onDataUpdate, religion, onReligionUpdate, preferences, onPreferencesUpdate }: UsageCalendarProps) {
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
  const [editNicotineCount, setEditNicotineCount] = useState('');
  const [editWeedCount, setEditWeedCount] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const { theme } = useTheme();

  // Pre-index usage data for O(1) lookups during calendar rendering
  const indexedUsage = useMemo(() => {
    const map = new Map<string, { nicotine: number; weed: number }>();
    for (const entry of usageData) {
      const current = map.get(entry.date) || { nicotine: 0, weed: 0 };
      if (entry.substance === 'nicotine') {
        current.nicotine = entry.count;
      } else if (entry.substance === 'weed') {
        current.weed = entry.count;
      }
      map.set(entry.date, current);
    }
    return map;
  }, [usageData]);

  const getUsageFromMap = (date: Date, substance: 'nicotine' | 'weed'): number => {
    const dateStr = getLocalDateString(date);
    const counts = indexedUsage.get(dateStr);
    return counts?.[substance] ?? 0;
  };

  const handleDateSelect = (date: Date | undefined) => {
    if (!date) return;

    // Don't allow future dates
    const today = new Date();
    today.setHours(23, 59, 59, 999);
    if (date > today) return;

    setSelectedDate(date);
    const nicotineCount = getUsageFromMap(date, 'nicotine');
    const weedCount = getUsageFromMap(date, 'weed');
    setEditNicotineCount(nicotineCount.toString());
    setEditWeedCount(weedCount.toString());
    setIsEditing(true);
  };

  const handleSave = async () => {
    if (selectedDate) {
      const dateStr = getLocalDateString(selectedDate);
      const todayStr = getTodayString();
      const newNicotineCount = parseInt(editNicotineCount, 10) || 0;
      const newWeedCount = parseInt(editWeedCount, 10) || 0;

      await Promise.all([
        setUsageForDateAsync(dateStr, newNicotineCount, 'nicotine'),
        setUsageForDateAsync(dateStr, newWeedCount, 'weed'),
      ]);

      // Update last usage time preferences if editing today's usage and count > 0
      if (dateStr === todayStr && preferences && onPreferencesUpdate) {
        const now = new Date().toISOString();
        const updatedPrefs = { ...preferences };

        if (newNicotineCount > 0) {
          updatedPrefs.lastNicotineUsageTime = now;
        }
        if (newWeedCount > 0) {
          updatedPrefs.lastWeedUsageTime = now;
        }

        // Only update if we changed something
        if (newNicotineCount > 0 || newWeedCount > 0) {
          await onPreferencesUpdate(updatedPrefs);
        }
      }

      onDataUpdate();
    }
    setIsEditing(false);
    setSelectedDate(undefined);
    setEditNicotineCount('');
    setEditWeedCount('');
  };

  const handleCancel = () => {
    setIsEditing(false);
    setSelectedDate(undefined);
    setEditNicotineCount('');
    setEditWeedCount('');
  };

  const handleClearDay = async () => {
    if (selectedDate) {
      const dateStr = getLocalDateString(selectedDate);
      await Promise.all([
        clearDayDataAsync(dateStr, 'nicotine'),
        clearDayDataAsync(dateStr, 'weed'),
      ]);
      onDataUpdate();
    }
    setIsEditing(false);
    setSelectedDate(undefined);
    setEditNicotineCount('');
    setEditWeedCount('');
  };

  const getColorStyle = useCallback((nicotineCount: number, weedCount: number, isToday: boolean): React.CSSProperties => {
    const hasNicotine = nicotineCount > 0;
    const hasWeed = weedCount > 0;

    // Current day - light gold hue (takes priority for styling the base)
    if (isToday && !hasNicotine && !hasWeed) {
      return {
        background: 'linear-gradient(135deg, rgba(251, 191, 36, 0.6) 0%, rgba(245, 158, 11, 0.7) 100%)',
        color: 'white',
      };
    }

    if (!hasNicotine && !hasWeed) {
      // No usage - lighter blue in light mode, standard blue in dark mode
      const blueGradient = theme === 'light'
        ? 'linear-gradient(135deg, rgba(147, 197, 253, 0.7) 0%, rgba(96, 165, 250, 0.8) 100%)'
        : 'linear-gradient(135deg, rgba(96, 165, 250, 0.5) 0%, rgba(59, 130, 246, 0.6) 100%)';
      return {
        background: blueGradient,
        color: 'white',
      };
    }

    if (hasNicotine && hasWeed) {
      // Both substances - split gradient (red/green)
      return {
        background: 'linear-gradient(135deg, rgba(239, 68, 68, 0.8) 0%, rgba(239, 68, 68, 0.6) 50%, rgba(34, 197, 94, 0.6) 50%, rgba(34, 197, 94, 0.8) 100%)',
        color: 'white',
      };
    }

    if (hasWeed) {
      // Marijuana only - green gradient
      const intensity = Math.min(weedCount / 10, 1);
      return {
        background: `linear-gradient(135deg, rgba(34, 197, 94, ${0.5 + intensity * 0.4}) 0%, rgba(22, 163, 74, ${0.6 + intensity * 0.4}) 100%)`,
        color: 'white',
      };
    }

    // Nicotine only - red gradient
    const intensity = Math.min(nicotineCount / 10, 1);
    return {
      background: `linear-gradient(135deg, rgba(239, 68, 68, ${0.5 + intensity * 0.4}) 0%, rgba(185, 28, 28, ${0.6 + intensity * 0.4}) 100%)`,
      color: 'white',
    };
  }, [theme]);

  const CustomDayButton = useCallback(({ day, modifiers, ...props }: DayButtonProps) => {
    const date = day.date;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const dateToCheck = new Date(date);
    dateToCheck.setHours(0, 0, 0, 0);
    const isFuture = dateToCheck > today;
    const isToday = dateToCheck.getTime() === today.getTime();

    const nicotineCount = isFuture ? 0 : getUsageFromMap(date, 'nicotine');
    const weedCount = isFuture ? 0 : getUsageFromMap(date, 'weed');
    const colorStyle = !isFuture ? getColorStyle(nicotineCount, weedCount, isToday) : {};

    return (
      <button
        {...props}
        style={!isFuture ? colorStyle : undefined}
        className={cn(
          "relative w-full h-full text-xs sm:text-sm transition-all hover:opacity-80",
          isFuture ? "text-muted-foreground opacity-30 cursor-not-allowed" : "cursor-pointer shadow-sm",
          isToday && "ring-2 ring-amber-400 ring-offset-2 ring-offset-background",
          props.className
        )}
        onClick={() => !isFuture && handleDateSelect(date)}
        disabled={isFuture}
      >
        <span className="font-semibold">{date.getDate()}</span>
        {(nicotineCount > 0 || weedCount > 0) && (
          <div className="absolute bottom-0.5 inset-x-0 flex justify-center gap-0.5">
            {nicotineCount > 0 && (
              <span className="text-[7px] leading-tight font-black bg-red-900/40 px-0.5 rounded-sm">
                •
              </span>
            )}
            {weedCount > 0 && (
              <span className="text-[7px] leading-tight font-black bg-green-900/40 px-0.5 rounded-sm">
                •
              </span>
            )}
          </div>
        )}
      </button>
    );
  }, [usageData, getColorStyle]);



  return (
    <>
      <Card className="bg-card/80 backdrop-blur-xl shadow-xl drop-shadow-lg transition-all duration-300 border-white/10 overflow-hidden">
        <CardContent className="p-2 sm:p-6">
          {/* Legend - Re-styled for better balance */}
          <div className="mb-8 flex flex-wrap items-center justify-center gap-x-6 gap-y-3 px-2 sm:px-4">
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full shadow-sm" style={{ background: 'linear-gradient(135deg, rgba(96,165,250,0.8), rgba(59,130,246,1))' }} />
              <span className="text-[10px] sm:text-xs font-semibold opacity-60 uppercase tracking-wider">No usage</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full shadow-sm" style={{ background: 'linear-gradient(135deg, rgba(251,191,36,0.8), rgba(245,158,11,1))' }} />
              <span className="text-[10px] sm:text-xs font-semibold opacity-60 uppercase tracking-wider">Today</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full shadow-sm" style={{ background: 'linear-gradient(135deg, rgba(239,68,68,0.8), rgba(185,28,28,1))' }} />
              <span className="text-[10px] sm:text-xs font-semibold opacity-60 uppercase tracking-wider">Nicotine</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full shadow-sm" style={{ background: 'linear-gradient(135deg, rgba(34,197,94,0.8), rgba(22,163,74,1))' }} />
              <span className="text-[10px] sm:text-xs font-semibold opacity-60 uppercase tracking-wider">Marijuana</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full shadow-sm" style={{ background: 'linear-gradient(135deg, rgba(239,68,68,0.8) 50%, rgba(34,197,94,0.8) 50%)' }} />
              <span className="text-[10px] sm:text-xs font-semibold opacity-60 uppercase tracking-wider">Both</span>
            </div>
          </div>

          <div className="flex flex-col lg:flex-row gap-8 lg:gap-8 items-center lg:items-stretch justify-center max-w-6xl mx-auto">
            {/* Calendar - Give it proper width on desktop */}
            <div className="w-full lg:w-1/2 flex flex-col items-center">
              <div className={cn(
                "rounded-2xl p-2 sm:p-4 border shadow-inner transition-all duration-500 w-full",
                theme === 'light' ? "bg-slate-50/50 border-slate-200/60" : "bg-black/20 border-white/5"
              )}>
                <DayPicker
                  mode="single"
                  selected={selectedDate}
                  onSelect={handleDateSelect}
                  className={cn(
                    "p-0 sm:p-2 w-full [&_.rdp-month]:w-full [&_.rdp-table]:w-full",
                    theme === 'light' ? "text-slate-900" : "text-white"
                  )}
                  showOutsideDays={false}
                  components={{
                    DayButton: (props) => (
                      <CustomDayButton
                        {...props}
                        className={cn(
                          props.className,
                          "aspect-square rounded-full flex items-center justify-center p-0"
                        )}
                      />
                    ),
                    Chevron: ({ orientation }) => (
                      <div className={cn(
                        "p-1.5 rounded-full border transition-all duration-200",
                        theme === 'light'
                          ? "bg-white border-slate-200 text-slate-600 hover:bg-slate-100 hover:scale-110 shadow-sm"
                          : "bg-white/5 border-white/10 text-white/70 hover:bg-white/10 hover:scale-110"
                      )}>
                        {orientation === 'left' ? (
                          <ChevronLeftIcon className="h-4 w-4" />
                        ) : (
                          <ChevronRightIcon className="h-4 w-4" />
                        )}
                      </div>
                    ),
                  }}
                />
              </div>
            </div>

            {/* Desktop Vertical Divider */}
            <div className="hidden lg:block w-px self-stretch bg-gradient-to-b from-transparent via-white/10 to-transparent" />

            {/* Daily Inspiration - Matching width on desktop */}
            <div className="w-full lg:w-1/2 flex flex-col justify-center">
              <DailyInspirationCard
                initialReligion={religion}
                onReligionChange={onReligionUpdate}
              />
            </div>
          </div>

        </CardContent>
      </Card>

      <Dialog open={isEditing} onOpenChange={(open) => !open && handleCancel()}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>
              Edit Usage for {selectedDate?.toLocaleDateString()}
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-full bg-red-500/20">
                  <Cigarette className="h-4 w-4 text-red-400" />
                </div>
                <div className="flex-1">
                  <Label htmlFor="nicotineCount" className="text-sm">Nicotine (puffs)</Label>
                  <Input
                    id="nicotineCount"
                    type="number"
                    min="0"
                    value={editNicotineCount}
                    onChange={(e) => setEditNicotineCount(e.target.value)}
                    className="text-center"
                  />
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-full bg-green-500/20">
                  <Leaf className="h-4 w-4 text-green-400" />
                </div>
                <div className="flex-1">
                  <Label htmlFor="weedCount" className="text-sm">Marijuana (hits)</Label>
                  <Input
                    id="weedCount"
                    type="number"
                    min="0"
                    value={editWeedCount}
                    onChange={(e) => setEditWeedCount(e.target.value)}
                    className="text-center"
                  />
                </div>
              </div>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={handleCancel} className="flex-1">
                Cancel
              </Button>
              <Button onClick={handleSave} className="flex-1">
                Save
              </Button>
            </div>
            <div className="pt-2 border-t">
              <Button
                variant="destructive"
                onClick={handleClearDay}
                className="w-full"
              >
                Clear This Day
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
export const UsageCalendar = React.memo(UsageCalendarComponent);
