import { useState, useMemo } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { api } from "../lib/api"
import { EmptyState } from "../components/EmptyState"
import { LoadingSpinner } from "../components/LoadingSpinner"
import type { TimeEntryInsert } from "@emberclone/shared"

export default function TimeEntries() {
  const queryClient = useQueryClient()
  
  const [formData, setFormData] = useState({
    description: "",
    startTime: "",
    endTime: "",
    projectId: ""
  })

  const [filters, setFilters] = useState({
    search: "",
    from: "",
    to: ""
  })

  const { data: entries, isLoading, isError } = useQuery({
    queryKey: ["time-entries", filters.from, filters.to],
    queryFn: () => api.listTimeEntries({ 
      from: filters.from || undefined, 
      to: filters.to || undefined 
    })
  })

  const createMutation = useMutation({
    mutationFn: (data: Partial<TimeEntryInsert>) => api.createTimeEntry(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["time-entries"] })
      setFormData({ description: "", startTime: "", endTime: "", projectId: "" })
    }
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.deleteTimeEntry(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["time-entries"] })
    }
  })

  const filteredEntries = useMemo(() => {
    if (!entries) return []
    return entries.filter(entry => 
      entry.description?.toLowerCase().includes(filters.search.toLowerCase())
    )
  }, [entries, filters.search])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    createMutation.mutate({
      description: formData.description,
      startTime: new Date(formData.startTime) as any,
      endTime: new Date(formData.endTime) as any,
      projectId: formData.projectId || undefined
    })
  }

  const handleExport = () => {
    const params = new URLSearchParams()
    if (filters.from) params.append("from", filters.from)
    if (filters.to) params.append("to", filters.to)
    window.location.href = `/api/time-entries/export.csv?${params.toString()}`
  }

  if (isError) return <div className="p-6 text-red-500">Error loading time entries.</div>

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <header>
        <h1 className="text-2xl font-bold text-gray-900">Time Tracking</h1>
        <p className="text-gray-500">Manage your work logs and project hours</p>
      </header>

      <section className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
        <h2 className="text-lg font-semibold mb-4">Log New Entry</h2>
        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="md:col-span-1">
            <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
            <input
              type="text"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="What did you work on?"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Start</label>
            <input
              type="datetime-local"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
              value={formData.startTime}
              onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">End</label>
            <input
              type="datetime-local"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
              value={formData.endTime}
              onChange={(e) => setFormData({ ...formData, endTime: e.target.value })}
            />
          </div>
          <div className="flex items-end">
            <button 
              type="submit" 
              disabled={createMutation.isPending}
              className="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {createMutation.isPending ? "Saving..." : "Save Entry"}
            </button>
          </div>
        </form>
      </section>

      <section className="space-y-4">
        <div className="flex flex-col md:flex-row gap-4 items-end justify-between bg-gray-50 p-4 rounded-lg border border-gray-200">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 flex-1">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1 uppercase">Search</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm outline-none focus:ring-2 focus:ring-blue-500"
                value={filters.search}
                onChange={(e) => setFilters({ ...filters, search: e.target.value })}
                placeholder="Filter by description..."
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1 uppercase">From</label>
              <input
                type="date"
                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm outline-none focus:ring-2 focus:ring-blue-500"
                value={filters.from}
                onChange={(e) => setFilters({ ...filters, from: e.target.value })}
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1 uppercase">To</label>
              <input
                type="date"
                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm outline-none focus:ring-2 focus:ring-blue-500"
                value={filters.to}
                onChange={(e) => setFilters({ ...filters, to: e.target.value })}
              />
            </div>
          </div>
          <button 
            onClick={handleExport}
            className="px-4 py-2 border border-gray-300 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-100 transition-colors"
          >
            Export CSV
          </button>
        </div>

        {isLoading ? (
          <div className="flex justify-center py-12"><LoadingSpinner /></div>
        ) : filteredEntries.length === 0 ? (
          <EmptyState message="No time entries found matching your criteria." />
        ) : (
          <div className="overflow-x-auto rounded-lg border border-gray-200">
            <table className="w-full text-left text-sm">
              <thead className="bg-gray-50 text-gray-600 font-medium border-b border-gray-200">
                <tr>
                  <th className="px-4 py-3">Description</th>
                  <th className="px-4 py-3">Start</th>
                  <th className="px-4 py-3">End</th>
                  <th className="px-4 py-3 text-right">Duration</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {filteredEntries.map((entry) => {
                  const duration = entry.endTime && entry.startTime 
                    ? (new Date(entry.endTime).getTime() - new Date(entry.startTime).getTime()) / 3600000 
                    : 0
                  return (
                    <tr key={entry.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-4 py-3 font-medium text-gray-900">{entry.description}</td>
                      <td className="px-4 py-3 text-gray-500">{new Date(entry.startTime).toLocaleString()}</td>
                      <td className="px-4 py-3 text-gray-500">{new Date(entry.endTime).toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-gray-600">{duration.toFixed(2)}h</td>
                      <td className="px-4 py-3 text-right">
                        <button 
                          onClick={() => deleteMutation.mutate(entry.id)}
                          className="text-red-500 hover:text-red-700 font-medium"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  )
}