import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Timer, Play, Square, ExternalLink } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface TimerPopoverProps {
  userId?: string;
  associations: { id: string; name: string }[];
}

const STORAGE_KEY = "active_time_entry";

function formatElapsed(seconds: number) {
  const h = Math.floor(seconds / 3600).toString().padStart(2, "0");
  const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, "0");
  const s = (seconds % 60).toString().padStart(2, "0");
  return `${h}:${m}:${s}`;
}

export function TimerPopover({ userId, associations }: TimerPopoverProps) {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [startTime, setStartTime] = useState<number | null>(null);
  const [elapsed, setElapsed] = useState(0);
  const [associationId, setAssociationId] = useState<string>("");
  const [description, setDescription] = useState("");
  const intervalRef = useRef<ReturnType<typeof setInterval>>();

  // Restore from localStorage
  useEffect(() => {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      try {
        const data = JSON.parse(raw);
        setActiveId(data.id);
        setStartTime(data.startTime);
        setAssociationId(data.associationId || "");
        setDescription(data.description || "");
      } catch {}
    }
  }, []);

  // Tick every second when running
  useEffect(() => {
    if (startTime) {
      const tick = () => setElapsed(Math.floor((Date.now() - startTime) / 1000));
      tick();
      intervalRef.current = setInterval(tick, 1000);
      return () => clearInterval(intervalRef.current);
    } else {
      setElapsed(0);
    }
  }, [startTime]);

  const handleStart = async () => {
    if (!userId) return;
    const now = new Date();
    const { data, error } = await supabase
      .from("time_entries")
      .insert({
        user_id: userId,
        association_id: associationId || null,
        description: description || null,
        start_time: now.toISOString(),
        is_running: true,
      })
      .select("id")
      .single();
    if (error || !data) {
      toast({ title: "Failed to start timer", description: error?.message, variant: "destructive" });
      return;
    }
    setActiveId(data.id);
    setStartTime(now.getTime());
    localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({ id: data.id, startTime: now.getTime(), associationId, description })
    );
    toast({ title: "Timer started" });
  };

  const handleStop = async () => {
    if (!activeId || !startTime) return;
    const end = new Date();
    const duration = Math.floor((end.getTime() - startTime) / 1000);
    const { error } = await supabase
      .from("time_entries")
      .update({
        end_time: end.toISOString(),
        duration_seconds: duration,
        is_running: false,
        association_id: associationId || null,
        description: description || null,
      })
      .eq("id", activeId);
    if (error) {
      toast({ title: "Failed to stop timer", description: error.message, variant: "destructive" });
      return;
    }
    setActiveId(null);
    setStartTime(null);
    setDescription("");
    setAssociationId("");
    localStorage.removeItem(STORAGE_KEY);
    toast({ title: "Time entry saved", description: formatElapsed(duration) });
  };

  // Persist edits while running
  useEffect(() => {
    if (activeId && startTime) {
      localStorage.setItem(
        STORAGE_KEY,
        JSON.stringify({ id: activeId, startTime, associationId, description })
      );
    }
  }, [associationId, description, activeId, startTime]);

  const isRunning = !!activeId;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <Tooltip>
        <TooltipTrigger asChild>
          <PopoverTrigger asChild>
            <Button
              variant="ghost"
              size="sm"
              className={`h-7 px-2 text-muted-foreground hover:text-foreground gap-1.5 ${
                isRunning ? "text-primary" : ""
              }`}
            >
              <Timer className="h-3.5 w-3.5" />
              {isRunning && (
                <span className="text-[11px] font-mono tabular-nums">{formatElapsed(elapsed)}</span>
              )}
            </Button>
          </PopoverTrigger>
        </TooltipTrigger>
        <TooltipContent>Time Tracker</TooltipContent>
      </Tooltip>
      <PopoverContent align="end" className="w-80 p-3">
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h4 className="text-[13px] font-semibold">Time Tracker</h4>
            <Button
              variant="ghost"
              size="sm"
              className="h-6 px-1.5 text-[11px]"
              onClick={() => {
                setOpen(false);
                navigate("/dashboard/time-tracking");
              }}
            >
              View all <ExternalLink className="h-3 w-3 ml-1" />
            </Button>
          </div>

          <div className="text-center py-2">
            <div className="text-3xl font-mono font-semibold tabular-nums">
              {formatElapsed(elapsed)}
            </div>
            <p className="text-[11px] text-muted-foreground mt-0.5">
              {isRunning ? "Running…" : "Stopped"}
            </p>
          </div>

          <div className="space-y-1.5">
            <Label className="text-[11px]">Client</Label>
            <Select value={associationId} onValueChange={setAssociationId}>
              <SelectTrigger className="h-8 text-[12px]">
                <SelectValue placeholder="Select a client (optional)" />
              </SelectTrigger>
              <SelectContent>
                {associations.map((a) => (
                  <SelectItem key={a.id} value={a.id} className="text-[12px]">
                    {a.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1.5">
            <Label className="text-[11px]">Description</Label>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="What are you working on?"
              className="text-[12px] min-h-[60px] resize-none"
            />
          </div>

          {!isRunning ? (
            <Button onClick={handleStart} size="sm" className="w-full h-8 text-[12px] gap-1.5">
              <Play className="h-3.5 w-3.5" /> Start Timer
            </Button>
          ) : (
            <Button
              onClick={handleStop}
              size="sm"
              variant="destructive"
              className="w-full h-8 text-[12px] gap-1.5"
            >
              <Square className="h-3.5 w-3.5" /> Stop & Save
            </Button>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
