import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Clock, Timer } from 'lucide-react';

interface TimeCompletionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (timeSpent: number) => void; // in minutes
  taskTitle: string;
}

export default function TimeCompletionModal({ isOpen, onClose, onSave, taskTitle }: TimeCompletionModalProps) {
  const [hours, setHours] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [manualHours, setManualHours] = useState('');
  const [activeTab, setActiveTab] = useState('clock');

  const handleSave = () => {
    let totalMinutes = 0;

    if (activeTab === 'clock') {
      totalMinutes = hours * 60 + minutes;
    } else {
      const parsedHours = parseFloat(manualHours) || 0;
      totalMinutes = Math.round(parsedHours * 60);
    }

    onSave(totalMinutes);
    console.log(`Time logged: ${totalMinutes} minutes for task: ${taskTitle}`);
    handleClose();
  };

  const handleClose = () => {
    setHours(0);
    setMinutes(0);
    setManualHours('');
    setActiveTab('clock');
    onClose();
  };

  const formatTime = (h: number, m: number) => {
    return `${h}h ${m}m`;
  };

  const getCurrentTimeDisplay = () => {
    if (activeTab === 'clock') {
      return formatTime(hours, minutes);
    } else {
      const parsedHours = parseFloat(manualHours) || 0;
      const h = Math.floor(parsedHours);
      const m = Math.round((parsedHours - h) * 60);
      return formatTime(h, m);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="w-[95vw] max-w-lg sm:max-w-md p-4 sm:p-6">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Timer className="w-4 h-4" />
            Task Completed!
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="text-center">
            <p className="text-sm text-muted-foreground mb-2">
              How much time did you spend on:
            </p>
            <p className="font-medium truncate" data-testid="text-completed-task-title">
              {taskTitle}
            </p>
          </div>

          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="clock" data-testid="tab-clock-picker">
                <Clock className="w-4 h-4 mr-2" />
                Clock
              </TabsTrigger>
              <TabsTrigger value="manual" data-testid="tab-manual-input">
                <Timer className="w-4 h-4 mr-2" />
                Manual
              </TabsTrigger>
            </TabsList>

            <TabsContent value="clock" className="space-y-4">
              {/* Apple-style Clock Picker */}
              <div className="space-y-4">
                <div className="text-center">
                  <div className="text-2xl font-mono" data-testid="text-clock-display">
                    {formatTime(hours, minutes)}
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  {/* Hours Picker */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-center block">Hours</label>
                    <div className="space-y-1 max-h-32 overflow-y-auto border rounded-md p-2">
                      {Array.from({ length: 13 }, (_, i) => (
                        <Button
                          key={i}
                          variant={hours === i ? "default" : "ghost"}
                          size="sm"
                          className="w-full"
                          onClick={() => setHours(i)}
                          data-testid={`button-hour-${i}`}
                        >
                          {i}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Minutes Picker */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-center block">Minutes</label>
                    <div className="space-y-1 max-h-32 overflow-y-auto border rounded-md p-2">
                      {Array.from({ length: 12 }, (_, i) => i * 5).map((minute) => (
                        <Button
                          key={minute}
                          variant={minutes === minute ? "default" : "ghost"}
                          size="sm"
                          className="w-full"
                          onClick={() => setMinutes(minute)}
                          data-testid={`button-minute-${minute}`}
                        >
                          {minute}
                        </Button>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="manual" className="space-y-4">
              {/* Manual Input */}
              <div className="space-y-3">
                <div className="text-center">
                  <div className="text-2xl font-mono" data-testid="text-manual-display">
                    {getCurrentTimeDisplay()}
                  </div>
                </div>

                <div>
                  <label className="text-sm font-medium block mb-2">Hours (decimal)</label>
                  <Input
                    type="number"
                    step="0.25"
                    min="0"
                    max="24"
                    placeholder="e.g., 1.5 for 1 hour 30 minutes"
                    value={manualHours}
                    onChange={(e) => setManualHours(e.target.value)}
                    data-testid="input-manual-hours"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Examples: 0.5 = 30min, 1.25 = 1h 15min, 2.75 = 2h 45min
                  </p>
                </div>
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex gap-3 pt-2">
            <Button
              variant="outline"
              onClick={handleClose}
              className="flex-1"
              data-testid="button-cancel-time"
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={activeTab === 'clock' ? hours === 0 && minutes === 0 : !manualHours.trim()}
              className="flex-1"
              data-testid="button-save-time"
            >
              Save Time
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}