'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';



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>;
}

export function UsageCalendar({ 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();

  const getUsageForDate = (date: Date, substance: 'nicotine' | 'weed'): number => {
    const dateStr = getLocalDateString(date);
    const entry = usageData.find((e) => e.date === dateStr && e.substance === substance);
    return entry?.count ?? 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 = getUsageForDate(date, 'nicotine');
    const weedCount = getUsageForDate(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 : getUsageForDate(date, 'nicotine');
    const weedCount = isFuture ? 0 : getUsageForDate(date, 'weed');
    const colorStyle = !isFuture ? getColorStyle(nicotineCount, weedCount, isToday) : {};

    return (
      <button
        {...props}
        style={!isFuture ? colorStyle : undefined}
        className={`relative w-full h-full p-2 text-sm rounded-md 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' : ''}`}
        onClick={() => !isFuture && handleDateSelect(date)}
        disabled={isFuture}
      >
        <span className="font-medium">{date.getDate()}</span>
        {(nicotineCount > 0 || weedCount > 0) && (
          <div className="absolute bottom-0.5 right-1 flex gap-0.5">
            {nicotineCount > 0 && (
              <span className="text-[9px] font-bold bg-red-900/50 px-1 rounded">
                {nicotineCount}
              </span>
            )}
            {weedCount > 0 && (
              <span className="text-[9px] font-bold bg-green-900/50 px-1 rounded">
                {weedCount}
              </span>
            )}
          </div>
        )}
      </button>
    );
  }, [usageData, getColorStyle]);



  return (
    <>
      <Card className="bg-card/80 backdrop-blur-xl shadow-xl drop-shadow-lg hover-lift transition-all duration-300 border-white/10 overflow-hidden">
        <CardContent className="p-3 sm:p-6">
          <div className="flex flex-col lg:flex-row gap-4">
            {/* Calendar */}
            <div className="w-full lg:w-auto overflow-x-auto block">
              <DayPicker
                mode="single"
                selected={selectedDate}
                onSelect={handleDateSelect}
                className={`rounded-md sm:border p-0 sm:p-3 w-full ${theme === 'light' ? 'text-slate-900 border-slate-200/20' : 'text-white border-white/20'}`}
                showOutsideDays={false}
                components={{
                  DayButton: CustomDayButton,
                  Chevron: ({ orientation }) => (
                    <div className={`p-1.5 rounded-full border ${theme === 'light' ? 'bg-white/50 border-slate-200/60 shadow-sm' : 'bg-slate-800/50 border-slate-700/60 shadow-sm'}`}>
                      {orientation === 'left' ? (
                        <ChevronLeftIcon className="h-4 w-4" />
                      ) : (
                        <ChevronRightIcon className="h-4 w-4" />
                      )}
                    </div>
                  ),
                }}
              />
            </div>

            {/* Daily Inspiration */}
            <DailyInspirationCard
              initialReligion={religion}
              onReligionChange={onReligionUpdate}
            />
          </div>

          <div className="mt-4 grid grid-cols-2 sm:grid-cols-3 md:flex md:flex-wrap gap-3 text-sm">
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded shrink-0" style={{ background: 'linear-gradient(135deg, rgba(96,165,250,0.5), rgba(59,130,246,0.6))' }} />
              <span>No usage</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded shrink-0" style={{ background: 'linear-gradient(135deg, rgba(251,191,36,0.6), rgba(245,158,11,0.7))' }} />
              <span>Today</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded shrink-0" style={{ background: 'linear-gradient(135deg, rgba(239,68,68,0.7), rgba(185,28,28,0.8))' }} />
              <span>Nicotine</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded shrink-0" style={{ background: 'linear-gradient(135deg, rgba(34,197,94,0.7), rgba(22,163,74,0.8))' }} />
              <span>Marijuana</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded shrink-0" style={{ background: 'linear-gradient(135deg, rgba(239,68,68,0.8) 50%, rgba(34,197,94,0.8) 50%)' }} />
              <span>Both</span>
            </div>
          </div>
          <p className="mt-2 text-xs text-muted-foreground">
            Click any day to edit the count
          </p>
        </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>
    </>
  );
}
