'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { ReminderSettings } from '@/lib/storage';
import { useNotifications } from '@/hooks/useNotifications';
import { useTheme } from '@/lib/theme-context';
import { Bell, BellOff, BellRing, Check, X } from 'lucide-react';

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface ReminderSettingsCardProps {
  settings: ReminderSettings;
  onSettingsChange: (settings: ReminderSettings) => void;
}

export function ReminderSettingsCard({
  settings,
  onSettingsChange,
}: ReminderSettingsCardProps) {
  const { theme } = useTheme();
  const { isSupported, permission, requestPermission } = useNotifications(settings);

  // Parse current time for initial state
  const [hours, minutes] = settings.reminderTime.split(':').map(Number);
  const currentAmpm = hours >= 12 ? 'PM' : 'AM';
  const currentHour12 = hours % 12 || 12; // Convert 0 -> 12, 13 -> 1, etc.

  const hourString = currentHour12.toString().padStart(2, '0');
  const minuteString = minutes.toString().padStart(2, '0');

  const handleToggle = async () => {
    if (!settings.enabled && permission !== 'granted') {
      const result = await requestPermission();
      if (result !== 'granted') return;
    }

    onSettingsChange({
      ...settings,
      enabled: !settings.enabled,
    });
  };

  const updateTime = (newHourStr: string, newMinuteStr: string, newAmpmStr: string) => {
    let h = parseInt(newHourStr);
    if (newAmpmStr === 'PM' && h !== 12) h += 12;
    if (newAmpmStr === 'AM' && h === 12) h = 0;

    const timeString = `${h.toString().padStart(2, '0')}:${newMinuteStr}`;

    onSettingsChange({
      ...settings,
      reminderTime: timeString,
    });
  };

  const cardBackground =
    theme === 'light'
      ? 'linear-gradient(135deg, rgba(79, 70, 229, 0.85) 0%, rgba(67, 56, 202, 0.9) 100%)'
      : 'linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(79, 70, 229, 0.15) 100%)';

  const getPermissionStatus = () => {
    if (!isSupported) return { text: 'Not supported', color: 'text-red-400' };
    if (permission === 'granted') return { text: 'Enabled', color: 'text-green-400' };
    if (permission === 'denied') return { text: 'Blocked', color: 'text-red-400' };
    return { text: 'Not set', color: 'text-yellow-400' };
  };

  const permissionStatus = getPermissionStatus();

  // Generate options
  const hoursOptions = Array.from({ length: 12 }, (_, i) => (i + 1).toString().padStart(2, '0'));
  const minutesOptions = Array.from({ length: 12 }, (_, i) => (i * 5).toString().padStart(2, '0'));

  return (
    <Card
      className="backdrop-blur-xl border border-indigo-500/40 shadow-xl drop-shadow-lg hover-lift transition-all duration-300 overflow-hidden relative"
      style={{ background: cardBackground }}
    >
      <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-indigo-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />

      <CardHeader className="relative z-10 pb-2">
        <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
          <Bell className="h-5 w-5 text-indigo-400" />
          <span>Daily Reminders</span>
        </CardTitle>
      </CardHeader>

      <CardContent className="relative z-10 space-y-4">
        {/* Permission Status */}
        <div className="flex items-center justify-between p-3 bg-white/10 rounded-lg">
          <span className="text-sm text-white/70">Notifications</span>
          <span className={`text-sm font-medium ${permissionStatus.color}`}>
            {permissionStatus.text}
          </span>
        </div>

        {/* Enable/Disable Toggle */}
        <div className="flex items-center justify-between p-3 bg-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            {settings.enabled ? (
              <BellRing className="h-4 w-4 text-indigo-300" />
            ) : (
              <BellOff className="h-4 w-4 text-white/50" />
            )}
            <span className="text-sm text-white">
              {settings.enabled ? 'Reminders On' : 'Reminders Off'}
            </span>
          </div>
          <button
            onClick={handleToggle}
            disabled={!isSupported || permission === 'denied'}
            className={`relative w-12 h-6 rounded-full transition-all duration-300 ${settings.enabled ? 'bg-indigo-500' : 'bg-white/20'
              } ${!isSupported || permission === 'denied' ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
          >
            <div
              className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-all duration-300 ${settings.enabled ? 'left-7' : 'left-1'
                }`}
            />
          </button>
        </div>

        {/* Time Picker */}
        {settings.enabled && (
          <div className="space-y-2">
            <Label className="text-white/70 text-sm">
              Reminder Time
            </Label>
            <div className="flex gap-2">
              {/* Hour Select */}
              <div className="flex-1">
                <Select
                  value={hourString}
                  onValueChange={(val) => updateTime(val, minuteString, currentAmpm)}
                >
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue placeholder="Hour" />
                  </SelectTrigger>
                  <SelectContent>
                    {hoursOptions.map((h) => (
                      <SelectItem key={h} value={h}>
                        {h}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Minute Select */}
              <div className="flex-1">
                <Select
                  value={minuteString}
                  onValueChange={(val) => updateTime(hourString, val, currentAmpm)}
                >
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue placeholder="Min" />
                  </SelectTrigger>
                  <SelectContent>
                    {minutesOptions.map((m) => (
                      <SelectItem key={m} value={m}>
                        {m}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* AM/PM Select */}
              <div className="w-24">
                <Select
                  value={currentAmpm}
                  onValueChange={(val) => updateTime(hourString, minuteString, val)}
                >
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue placeholder="AM/PM" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="AM">AM</SelectItem>
                    <SelectItem value="PM">PM</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <p className="text-xs text-white/50">
              You&apos;ll receive a reminder at this time each day
            </p>
          </div>
        )}

        {/* Request Permission Button */}
        {isSupported && permission === 'default' && (
          <Button
            onClick={requestPermission}
            variant="outline"
            className="w-full border-indigo-400/50 text-white hover:bg-white/10"
          >
            <Bell className="mr-2 h-4 w-4" />
            Enable Notifications
          </Button>
        )}

        {/* Denied Message */}
        {permission === 'denied' && (
          <div className="p-3 bg-red-500/20 border border-red-500/30 rounded-lg">
            <p className="text-xs text-red-300">
              Notifications are blocked. Please enable them in your browser settings to receive reminders.
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
