"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Play, Square, Plus, Trash2, Clock, Briefcase, User, TrendingUp, DollarSign } from "lucide-react"

interface TimeEntry {
  id: string
  description: string
  date: string
  duration_minutes: number
  billable: boolean
  hourly_rate: number
  user_name: string
  project_name: string
  created_at: string
}

export default function TimeTrackingPage() {
  const [entries, setEntries] = useState<TimeEntry[]>([])
  const [summary, setSummary] = useState<any>(null)
  const [projects, setProjects] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [showManual, setShowManual] = useState(false)

  // Manual entry form
  const [manualProject, setManualProject] = useState("")
  const [manualDesc, setManualDesc] = useState("")
  const [manualDate, setManualDate] = useState(new Date().toISOString().split("T")[0])
  const [manualHours, setManualHours] = useState("")
  const [manualMinutes, setManualMinutes] = useState("")
  const [manualBillable, setManualBillable] = useState(true)
  const [manualRate, setManualRate] = useState("")
  const [saving, setSaving] = useState(false)

  // Timer
  const [timerRunning, setTimerRunning] = useState(false)
  const [timerSeconds, setTimerSeconds] = useState(0)
  const [timerProject, setTimerProject] = useState("")
  const [timerDesc, setTimerDesc] = useState("")
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const startTimeRef = useRef<Date | null>(null)

  const fetchData = useCallback(async () => {
    try {
      const [eRes, sRes, pRes] = await Promise.all([
        fetch("/api/time-entries"),
        fetch("/api/time-entries/summary"),
        fetch("/api/projects"),
      ])
      if (eRes.ok) setEntries(await eRes.json()); else setEntries([])
      if (sRes.ok) setSummary(await sRes.json()); else setSummary(null)
      if (pRes.ok) setProjects(await pRes.json()); else setProjects([])
    } catch (e) {
      console.error("Failed to load time data", e)
      setEntries([])
      setProjects([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { fetchData() }, [fetchData])

  const startTimer = () => {
    if (!timerDesc.trim()) return
    setTimerRunning(true)
    setTimerSeconds(0)
    startTimeRef.current = new Date()
    timerRef.current = setInterval(() => {
      setTimerSeconds((prev) => prev + 1)
    }, 1000)
  }

  const stopTimer = async () => {
    if (timerRef.current) clearInterval(timerRef.current)
    setTimerRunning(false)

    if (timerSeconds < 60) return

    try {
      await fetch("/api/time-entries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectId: timerProject || null,
          description: timerDesc,
          date: new Date().toISOString().split("T")[0],
          startTime: startTimeRef.current?.toISOString(),
          endTime: new Date().toISOString(),
          durationMinutes: Math.round(timerSeconds / 60),
          billable: true,
          hourlyRate: null,
        }),
      })
      setTimerDesc("")
      setTimerProject("")
      setTimerSeconds(0)
      fetchData()
    } catch (e) {
      console.error("Failed to save time entry", e)
    }
  }

  const addManualEntry = async () => {
    const hours = parseInt(manualHours) || 0
    const mins = parseInt(manualMinutes) || 0
    const totalMins = hours * 60 + mins
    if (totalMins <= 0 || !manualDesc.trim()) return

    setSaving(true)
    try {
      await fetch("/api/time-entries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectId: manualProject || null,
          description: manualDesc,
          date: manualDate,
          durationMinutes: totalMins,
          billable: manualBillable,
          hourlyRate: manualRate ? parseFloat(manualRate) : null,
        }),
      })
      setManualDesc("")
      setManualHours("")
      setManualMinutes("")
      setManualRate("")
      setShowManual(false)
      fetchData()
    } finally {
      setSaving(false)
    }
  }

  const deleteEntry = async (id: string) => {
    await fetch(`/api/time-entries?id=${id}`, { method: "DELETE" })
    fetchData()
  }

  const formatDuration = (mins: number) => {
    const h = Math.floor(mins / 60)
    const m = mins % 60
    return h > 0 ? `${h}h ${m}m` : `${m}m`
  }

  const formatTimer = (secs: number) => {
    const h = Math.floor(secs / 3600)
    const m = Math.floor((secs % 3600) / 60)
    const s = secs % 60
    return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`
  }

  const formatCurrency = (n: number) => `R${Number(n).toLocaleString(undefined, { minimumFractionDigits: 2 })}`

  if (loading) {
    return (
      <div className="space-y-4">
        <PageHeader title="Time Tracking" description="Track billable hours" />
        <div className="grid gap-4 md:grid-cols-4">{[1, 2, 3, 4].map((i) => <div key={i} className="h-24 animate-pulse rounded-lg bg-muted" />)}</div>
      </div>
    )
  }

  const t = summary?.totals || { total_minutes: 0, billable_minutes: 0, total_revenue: 0, entry_count: 0 }

  return (
    <div className="space-y-6">
      <PageHeader title="Time Tracking" description="Track billable hours per project" />

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Total Hours</p>
          <p className="text-2xl font-bold">{formatDuration(parseInt(t.total_minutes))}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Billable Hours</p>
          <p className="text-2xl font-bold">{formatDuration(parseInt(t.billable_minutes))}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Revenue</p>
          <p className="text-2xl font-bold">{formatCurrency(parseFloat(t.total_revenue))}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Entries</p>
          <p className="text-2xl font-bold">{t.entry_count}</p>
        </Card>
      </div>

      {/* Timer */}
      <Card className="p-6">
        <p className="text-sm font-medium mb-3 flex items-center gap-2"><Clock className="h-4 w-4" /> Stopwatch</p>
        <div className="flex items-end gap-3">
          <div className="flex-1 space-y-2">
            <Input placeholder="What are you working on?" value={timerDesc} onChange={(e) => setTimerDesc(e.target.value)} className="h-9" disabled={timerRunning} />
            <select value={timerProject} onChange={(e) => setTimerProject(e.target.value)} className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm" disabled={timerRunning}>
              <option value="">No project</option>
              {projects.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>
          <div className="text-3xl font-mono font-bold tabular-nums px-4 py-1">{formatTimer(timerSeconds)}</div>
          {!timerRunning ? (
            <Button onClick={startTimer} disabled={!timerDesc.trim()}><Play className="mr-1.5 h-4 w-4" /> Start</Button>
          ) : (
            <Button variant="destructive" onClick={stopTimer}><Square className="mr-1.5 h-4 w-4" /> Stop</Button>
          )}
        </div>
      </Card>

      {/* Manual Entry */}
      <Card className="p-4">
        <div className="flex items-center justify-between mb-3">
          <p className="text-sm font-medium">Manual Entry</p>
          <Button size="sm" variant="outline" onClick={() => setShowManual(!showManual)}>
            <Plus className="h-3.5 w-3.5 mr-1" /> {showManual ? "Cancel" : "Add Entry"}
          </Button>
        </div>
        {showManual && (
          <div className="space-y-3 p-3 rounded-lg border bg-muted/20">
            <div className="grid gap-3 md:grid-cols-2">
              <Input placeholder="Description *" value={manualDesc} onChange={(e) => setManualDesc(e.target.value)} className="h-8 text-sm" />
              <select value={manualProject} onChange={(e) => setManualProject(e.target.value)} className="flex h-8 w-full rounded-md border border-input bg-transparent px-3 text-sm shadow-sm">
                <option value="">No project</option>
                {projects.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>
            <div className="flex gap-3 flex-wrap">
              <Input type="date" value={manualDate} onChange={(e) => setManualDate(e.target.value)} className="h-8 w-40 text-sm" />
              <Input type="number" placeholder="Hours" value={manualHours} onChange={(e) => setManualHours(e.target.value)} className="h-8 w-24 text-sm" min="0" />
              <Input type="number" placeholder="Minutes" value={manualMinutes} onChange={(e) => setManualMinutes(e.target.value)} className="h-8 w-24 text-sm" min="0" />
              <Input type="number" placeholder="Rate (ZAR/hr)" value={manualRate} onChange={(e) => setManualRate(e.target.value)} className="h-8 w-32 text-sm" min="0" />
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={manualBillable} onChange={(e) => setManualBillable(e.target.checked)} className="rounded" />
                Billable
              </label>
            </div>
            <Button size="sm" onClick={addManualEntry} disabled={saving || !manualDesc.trim()}>
              {saving ? "Saving..." : "Save Entry"}
            </Button>
          </div>
        )}
      </Card>

      {/* Per-project summary */}
      {summary?.perProject?.length > 0 && (
        <Card className="p-4">
          <p className="text-sm font-medium mb-3 flex items-center gap-2"><Briefcase className="h-4 w-4" /> Hours by Project</p>
          <div className="space-y-2">
            {summary.perProject.map((p: any) => (
              <div key={p.id} className="flex items-center gap-3 text-sm">
                <span className="w-48 truncate">{p.name}</span>
                <div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
                  <div className="h-full rounded-full bg-primary" style={{ width: `${Math.min(100, (parseInt(p.total_minutes) / parseInt(t.total_minutes)) * 100)}%` }} />
                </div>
                <span className="w-20 text-right">{formatDuration(parseInt(p.total_minutes))}</span>
                <span className="w-24 text-right text-muted-foreground">{formatCurrency(parseFloat(p.revenue))}</span>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Recent Entries */}
      <Card className="divide-y">
        <div className="flex items-center justify-between px-4 py-3">
          <p className="text-sm font-medium">Recent Entries</p>
        </div>
        {entries.length === 0 && (
          <div className="p-8 text-center text-sm text-muted-foreground">No entries yet</div>
        )}
        {entries.map((entry) => (
          <div key={entry.id} className="flex items-center gap-3 px-4 py-3 text-sm hover:bg-muted/30">
            <span className={`h-2 w-2 rounded-full shrink-0 ${entry.billable ? "bg-emerald-500" : "bg-zinc-400"}`} />
            <div className="flex-1 min-w-0">
              <p className="truncate">{entry.description || "No description"}</p>
              <p className="text-xs text-muted-foreground">
                {entry.project_name && <>{entry.project_name} · </>}
                {entry.user_name} · {new Date(entry.date).toLocaleDateString()}
              </p>
            </div>
            <span className="font-medium">{formatDuration(entry.duration_minutes)}</span>
            {entry.hourly_rate > 0 && <span className="text-muted-foreground w-20 text-right">{formatCurrency(entry.duration_minutes * entry.hourly_rate / 60)}</span>}
            <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => deleteEntry(entry.id)}>
              <Trash2 className="h-3.5 w-3.5 text-red-400" />
            </Button>
          </div>
        ))}
      </Card>
    </div>
  )
}
