"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card } from "@/components/ui/card"
import { Search, Plus, Calendar, User, Building2, ArrowRight, DollarSign } from "lucide-react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

interface Project {
  id: string
  name: string
  description: string
  start_date: string
  target_end_date: string
  actual_end_date: string
  budget: number
  created_at: string
  status_name: string
  status_color: string
  customer_id: string
  company_name: string
  owner_id: string
  owner_name: string
  owner_avatar: string
}

interface ProjectStatus {
  id: string
  name: string
  color: string
  sort_order: number
}

export default function ProjectsPage() {
  const router = useRouter()
  const [projects, setProjects] = useState<Project[]>([])
  const [statuses, setStatuses] = useState<ProjectStatus[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")

  const fetchProjects = async () => {
    try {
      const params = new URLSearchParams()
      if (search) params.set("search", search)
      if (statusFilter !== "all") params.set("status", statusFilter)
      const res = await fetch(`/api/projects?${params}`)
      if (res.ok) setProjects(await res.json()); else setProjects([])
    } catch (e) {
      console.error("Failed to load projects", e)
      setProjects([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchProjects() }, [search, statusFilter])

  useEffect(() => {
    fetch("/api/project-statuses").then(r => r.json()).then(setStatuses).catch(() => {})
  }, [])

  const formatDate = (d: string) => d ? new Date(d).toLocaleDateString() : "—"
  const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : ""

  return (
    <div className="space-y-4">
      <PageHeader title="Projects" description="Track post-sale project delivery">
        <NewProjectDialog statuses={statuses} onCreated={() => fetchProjects()} />
      </PageHeader>

      <Card>
        <div className="p-4">
          <div className="flex flex-1 flex-col gap-4 sm:flex-row sm:items-center">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search projects or companies..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="h-9 pl-9 w-full sm:max-w-sm"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="h-9 w-[160px]">
                <SelectValue placeholder="All Statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                {statuses.map((s) => (
                  <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="divide-y">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : projects.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">No projects yet</div>
          ) : (
            projects.map((p) => (
              <div
                key={p.id}
                className="flex items-center gap-4 px-6 py-4 hover:bg-muted/50 cursor-pointer transition-colors"
                onClick={() => router.push(`/projects/${p.id}`)}
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium truncate">{p.name}</span>
                    <Badge
                      variant="outline"
                      className="shrink-0"
                      style={{ borderColor: p.status_color + "40", color: p.status_color }}
                    >
                      {p.status_name}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
                    <span className="flex items-center gap-1"><Building2 className="h-3.5 w-3.5" />{p.company_name}</span>
                    <span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{p.owner_name}</span>
                    <span className="flex items-center gap-1"><Calendar className="h-3.5 w-3.5" />{formatDate(p.start_date)} — {formatDate(p.target_end_date)}</span>
                    {p.budget > 0 && <span className="flex items-center gap-1"><DollarSign className="h-3.5 w-3.5" />{formatCurrency(p.budget)}</span>}
                  </div>
                </div>
                <ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
              </div>
            ))
          )}
        </div>
      </Card>
    </div>
  )
}

function NewProjectDialog({ statuses, onCreated }: { statuses: ProjectStatus[]; onCreated: () => void }) {
  const [open, setOpen] = useState(false)
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [customerId, setCustomerId] = useState("")
  const [ownerId, setOwnerId] = useState("")
  const [startDate, setStartDate] = useState("")
  const [targetEndDate, setTargetEndDate] = useState("")
  const [budget, setBudget] = useState("")
  const [customers, setCustomers] = useState<any[]>([])
  const [users, setUsers] = useState<any[]>([])
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    if (!open) return
    fetch("/api/customers?limit=100").then(r => r.json()).then(setCustomers).catch(() => {})
    fetch("/api/users").then(r => r.json()).then(d => setUsers(d.users || [])).catch(() => {})
  }, [open])

  const handleSubmit = async () => {
    if (!name || !customerId) return
    setSaving(true)
    try {
      const res = await fetch("/api/projects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          description,
          customerId,
          ownerId: ownerId || undefined,
          startDate: startDate || null,
          targetEndDate: targetEndDate || null,
          budget: budget ? parseFloat(budget) : null,
        }),
      })
      if (res.ok) {
        setOpen(false)
        setName(""); setDescription(""); setCustomerId(""); setOwnerId(""); setStartDate(""); setTargetEndDate(""); setBudget("")
        onCreated()
      }
    } finally {
      setSaving(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm"><Plus className="mr-1.5 h-4 w-4" />New Project</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create Project</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium">Project Name *</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Website Redesign" />
          </div>
          <div>
            <label className="text-sm font-medium">Customer *</label>
            <select
              value={customerId}
              onChange={(e) => setCustomerId(e.target.value)}
              className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
            >
              <option value="">Select customer...</option>
              {customers.map((c: any) => (
                <option key={c.id} value={c.id}>{c.company_name || `${c.first_name} ${c.last_name}`}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="text-sm font-medium">Project Owner</label>
            <select
              value={ownerId}
              onChange={(e) => setOwnerId(e.target.value)}
              className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
            >
              <option value="">Select owner...</option>
              {users.map((u: any) => (
                <option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium">Start Date</label>
              <Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
            </div>
            <div>
              <label className="text-sm font-medium">Target End Date</label>
              <Input type="date" value={targetEndDate} onChange={(e) => setTargetEndDate(e.target.value)} />
            </div>
          </div>
          <div>
            <label className="text-sm font-medium">Budget (ZAR)</label>
            <Input type="number" value={budget} onChange={(e) => setBudget(e.target.value)} placeholder="e.g. 25000" />
          </div>
          <div>
            <label className="text-sm font-medium">Description</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm"
              placeholder="Project scope and notes..."
            />
          </div>
          <div className="flex justify-end gap-3">
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button onClick={handleSubmit} disabled={saving || !name || !customerId}>
              {saving ? "Creating..." : "Create Project"}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
