import { useState, useEffect } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { Copy, Trash2, Edit3, X, Plus, Archive, ArchiveRestore, Euro, Search, Loader2 } from "lucide-react"
import { api } from "../lib/api"
import { useToast } from "../hooks/use-toast"
import { Breadcrumb } from "../components/ui/Breadcrumb"

function TableSkeleton() {
  return (
    <div className="space-y-3 animate-pulse">
      {[...Array(5)].map((_, i) => (
        <div key={i} className="h-12 bg-gray-100 dark:bg-gray-800 rounded-lg w-full" />
      ))}
    </div>
  )
}

export default function Projects() {
  const queryClient = useQueryClient()
  const { toast } = useToast()
  const [name, setName] = useState("")
  const [icon, setIcon] = useState("")
  const [customerId, setCustomerId] = useState("")
  const [billingRate, setBillingRate] = useState("")
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [bulkPrefix, setBulkPrefix] = useState("")
  const [editingProject, setEditingProject] = useState<{ id: string; name: string; budget: number } | null>(null)
  const [showArchived, setShowArchived] = useState(false)
  const [searchTerm, setSearchTerm] = useState("")

  const { data: projects, isLoading: projectsLoading, isError: projectsError } = useQuery({
    queryKey: ["projects"],
    queryFn: () => api.listProjects()
  })

  const { data: customers, isLoading: customersLoading } = useQuery({
    queryKey: ["customers"],
    queryFn: () => api.listCustomers()
  })

  useEffect(() => {
    if (projects) {
      projects.forEach((project: any) => {
        const budget = project.budget || 0
        const usedHours = project.usedHours || 0
        if (budget === 0) return

        const ratio = usedHours / budget
        if (ratio > 1) {
          toast.error(`Budget für ${project.name} überschritten!`)
        } else if (ratio >= 0.8) {
          toast.info(`Budget für ${project.name} bei ${Math.round(ratio * 100)}%`)
        }
      })
    }
  }, [projects, toast])

  const createMutation = useMutation({
    mutationFn: ({ name, customerId, icon, billingRate }: { name: string; customerId: string; icon: string; billingRate: number }) => 
      api.createProject({ name, customerId, icon, billingRate }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      setName("")
      setCustomerId("")
      setIcon("")
      setBillingRate("")
      toast.success("Projekt erstellt")
    }
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => 
      api.updateProject(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      setEditingProject(null)
      toast.success("Projekt aktualisiert")
    }
  })

  const cloneMutation = useMutation({
    mutationFn: (id: string) => api.cloneProject(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      toast.success("Projekt geklont")
    }
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.deleteProject(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      toast.success("Projekt gelöscht")
    }
  })

  const bulkRenameMutation = useMutation({
    mutationFn: ({ ids, prefix }: { ids: string[]; prefix: string }) => 
      api.bulkRenameProjects(ids, prefix),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      setSelectedIds([])
      setBulkPrefix("")
      toast.success("Projekte umbenannt")
    }
  })

  const bulkDeleteMutation = useMutation({
    mutationFn: (ids: string[]) => api.bulkDeleteProjects(ids),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["projects"] })
      setSelectedIds([])
      toast.success("Projekte gelöscht")
    }
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!name.trim() || !customerId) return
    const rateInCents = Math.round(parseFloat(billingRate || "0") * 100)
    createMutation.mutate({ name, customerId, icon, billingRate: rateInCents })
  }

  const handleBulkRename = (e: React.FormEvent) => {
    e.preventDefault()
    if (!bulkPrefix.trim() || selectedIds.length === 0) return
    bulkRenameMutation.mutate({ ids: selectedIds, prefix: bulkPrefix })
  }

  const toggleSelectAll = () => {
    const filtered = projects?.filter(p => 
      p.name.toLowerCase().includes(searchTerm.toLowerCase()) && 
      (showArchived ? p.archived : !p.archived)
    ) || []
    if (selectedIds.length === filtered.length) {
      setSelectedIds([])
    } else {
      setSelectedIds(filtered.map((p: any) => p.id))
    }
  }

  const filteredProjects = projects?.filter((p: any) => {
    const matchesSearch = p.name.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesArchive = showArchived ? p.archived : !p.archived
    return matchesSearch && matchesArchive
  }) || []

  if (projectsLoading || customersLoading) {
    return (
      <div className="p-6 max-w-6xl mx-auto">
        <Breadcrumb items={[{ label: "Projects", href: "/projects" }]} />
        <div className="mt-8 space-y-6">
          <div className="h-20 bg-gray-100 dark:bg-gray-800 rounded-lg animate-pulse w-1/3" />
          <TableSkeleton />
        </div>
      </div>
    )
  }

  if (projectsError) {
    return <div className="p-6 text-red-500">Error loading projects.</div>
  }

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <Breadcrumb items={[{ label: "Projects", href: "/projects" }]} />

      <div className="mt-8 grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-1 space-y-6">
          <div className="bg-white dark:bg-gray-900 p-6 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Plus className="w-5 h-5" /> New Project
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Project Name</label>
                <input 
                  value={name} onChange={e => setName(e.target.value)}
                  className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700" 
                  placeholder="e.g. Website Redesign"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Customer</label>
                <select 
                  value={customerId} onChange={e => setCustomerId(e.target.value)}
                  className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700"
                >
                  <option value="">Select Customer</option>
                  {customers?.map((c: any) => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">Icon</label>
                  <input 
                    value={icon} onChange={e => setIcon(e.target.value)}
                    className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700" 
                    placeholder="🚀"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Rate (€)</label>
                  <input 
                    type="number" step="0.01" value={billingRate} onChange={e => setBillingRate(e.target.value)}
                    className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700" 
                    placeholder="0.00"
                  />
                </div>
              </div>
              <button 
                disabled={createMutation.isPending}
                className="w-full bg-blue-600 text-white p-2 rounded hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {createMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                Create Project
              </button>
            </form>
          </div>
        </div>

        <div className="lg:col-span-2 space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="relative flex-1 min-w-[300px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input 
                value={searchTerm} onChange={e => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 rounded-lg border dark:bg-gray-900 dark:border-gray-800" 
                placeholder="Search projects..."
              />
            </div>
            <button 
              onClick={() => setShowArchived(!showArchived)}
              className={`p-2 rounded-lg border flex items-center gap-2 transition-colors ${showArchived ? 'bg-blue-50 border-blue-200 text-blue-600' : 'bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-800'}`}
            >
              {showArchived ? <ArchiveRestore className="w-4 h-4" /> : <Archive className="w-4 h-4" />}
              {showArchived ? "Show Active" : "Show Archived"}
            </button>
          </div>

          {selectedIds.length > 0 && (
            <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-100 dark:border-blue-800 flex items-center justify-between gap-4">
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium">{selectedIds.length} selected</span>
                <form onSubmit={handleBulkRename} className="flex gap-2">
                  <input 
                    value={bulkPrefix} onChange={e => setBulkPrefix(e.target.value)}
                    className="p-1 text-sm rounded border dark:bg-gray-800 dark:border-gray-700" 
                    placeholder="Prefix for rename..."
                  />
                  <button className="text-xs bg-blue-600 text-white px-2 py-1 rounded">Rename</button>
                </form>
              </div>
              <button 
                onClick={() => { if(confirm("Delete selected?")) bulkDeleteMutation.mutate(selectedIds) }}
                className="text-red-600 hover:text-red-700 flex items-center gap-1 text-sm"
              >
                <Trash2 className="w-4 h-4" /> Delete
              </button>
            </div>
          )}

          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
            <table className="w-full text-left border-collapse">
              <thead className="bg-gray-50 dark:bg-gray-800/50 text-sm text-gray-500">
                <tr>
                  <th className="p-4 w-10">
                    <input type="checkbox" onChange={toggleSelectAll} checked={selectedIds.length === filteredProjects.length && filteredProjects.length > 0} />
                  </th>
                  <th className="p-4 font-medium">Project</th>
                  <th className="p-4 font-medium">Rate</th>
                  <th className="p-4 font-medium text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                {filteredProjects.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="p-8 text-center text-gray-500">No projects found.</td>
                  </tr>
                ) : (
                  filteredProjects.map((project: any) => (
                    <tr key={project.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                      <td className="p-4">
                        <input 
                          type="checkbox" 
                          checked={selectedIds.includes(project.id)} 
                          onChange={e => {
                            if (e.target.checked) setSelectedIds([...selectedIds, project.id])
                            else setSelectedIds(selectedIds.filter(id => id !== project.id))
                          }} 
                        />
                      </td>
                      <td className="p-4">
                        <div className="flex items-center gap-3">
                          <span className="text-xl">{project.icon || "📁"}</span>
                          <div>
                            <div className="font-medium">{project.name}</div>
                            <div className="text-xs text-gray-500">{project.customer?.name || "No customer"}</div>
                          </div>
                        </div>
                      </td>
                      <td className="p-4">
                        <div className="flex items-center gap-1 text-sm">
                          <Euro className="w-3 h-3" />
                          {(project.billingRate / 100).toFixed(2)}
                        </div>
                      </td>
                      <td className="p-4 text-right">
                        <div className="flex justify-end gap-2">
                          <button onClick={() => setEditingProject({ id: project.id, name: project.name, budget: project.budget || 0 })} className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-600 dark:text-gray-400">
                            <Edit3 className="w-4 h-4" />
                          </button>
                          <button onClick={() => cloneMutation.mutate(project.id)} className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-600 dark:text-gray-400">
                            <Copy className="w-4 h-4" />
                          </button>
                          <button onClick={() => { if(confirm("Delete project?")) deleteMutation.mutate(project.id) }} className="p-1.5 hover:bg-red-50 dark:hover:bg-red-900/20 rounded text-red-600">
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {editingProject && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-900 p-6 rounded-xl max-w-md w-full shadow-xl">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">Edit Project</h3>
              <button onClick={() => setEditingProject(null)}><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Name</label>
                <input 
                  value={editingProject.name} 
                  onChange={e => setEditingProject({ ...editingProject, name: e.target.value })}
                  className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700" 
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Budget (Hours)</label>
                <input 
                  type="number" value={editingProject.budget} 
                  onChange={e => setEditingProject({ ...editingProject, budget: parseFloat(e.target.value) })}
                  className="w-full p-2 rounded border dark:bg-gray-800 dark:border-gray-700" 
                />
              </div>
              <button 
                onClick={() => updateMutation.mutate({ id: editingProject.id, data: editingProject })}
                disabled={updateMutation.isPending}
                className="w-full bg-blue-600 text-white p-2 rounded hover:bg-blue-700 disabled:opacity-50"
              >
                {updateMutation.isPending ? "Saving..." : "Save Changes"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}