"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
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 { Plus, Trash2, ArrowLeft, FileText } from "lucide-react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

interface LineItem {
  id: string
  description: string
  quantity: number
  unitPrice: number
  discountPercent: number
  totalPrice: number
}

export default function NewProposalPage() {
  const router = useRouter()
  const [title, setTitle] = useState("")
  const [leadId, setLeadId] = useState("")
  const [customerId, setCustomerId] = useState("")
  const [validUntil, setValidUntil] = useState("")
  const [taxPercent, setTaxPercent] = useState(15)
  const [notes, setNotes] = useState("")
  const [terms, setTerms] = useState("Payment due within 30 days. 50% deposit required to commence work.")
  const [items, setItems] = useState<LineItem[]>([])
  const [leads, setLeads] = useState<any[]>([])
  const [customers, setCustomers] = useState<any[]>([])
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    fetch("/api/leads?limit=100").then((r) => r.json()).then(setLeads).catch(() => {})
    fetch("/api/customers?limit=100").then((r) => r.json()).then(setCustomers).catch(() => {})
  }, [])

  const addItem = () => {
    setItems((prev) => [
      ...prev,
      { id: crypto.randomUUID(), description: "", quantity: 1, unitPrice: 0, discountPercent: 0, totalPrice: 0 },
    ])
  }

  const updateItem = (id: string, field: keyof LineItem, value: string | number) => {
    setItems((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item
        const updated = { ...item, [field]: value }
        updated.totalPrice = updated.quantity * updated.unitPrice * (1 - updated.discountPercent / 100)
        return updated
      })
    )
  }

  const removeItem = (id: string) => {
    setItems((prev) => prev.filter((i) => i.id !== id))
  }

  const subtotal = items.reduce((sum, i) => sum + i.totalPrice, 0)
  const taxAmount = subtotal * (taxPercent / 100)
  const total = subtotal + taxAmount

  const handleSubmit = async () => {
    if (!title) return
    setSaving(true)
    try {
      const res = await fetch("/api/proposals", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title,
          leadId: leadId || null,
          customerId: customerId || null,
          subtotal,
          taxPercent,
          taxAmount,
          totalAmount: total,
          validUntil: validUntil || null,
          notes: notes || null,
          terms: terms || null,
        }),
      })
      const data = await res.json()
      if (!data.id) throw new Error("No id returned")

      for (const item of items) {
        await fetch(`/api/proposals/${data.id}/items`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            description: item.description,
            quantity: item.quantity,
            unitPrice: item.unitPrice,
            discountPercent: item.discountPercent,
          }),
        })
      }

      router.push(`/proposals/${data.id}`)
    } catch (e) {
      console.error("Failed to create proposal", e)
    } finally {
      setSaving(false)
    }
  }

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

  return (
    <div className="space-y-6 max-w-4xl mx-auto">
      <PageHeader title="New Proposal" description="Create a professional quote for your client">
        <Button variant="outline" size="sm" onClick={() => router.push("/proposals")}>
          <ArrowLeft className="mr-1.5 h-4 w-4" /> Back
        </Button>
      </PageHeader>

      <Card className="p-6 space-y-6">
        <div className="grid gap-4 md:grid-cols-2">
          <div>
            <label className="text-sm font-medium">Proposal Title *</label>
            <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Website Redesign Quote" />
          </div>
          <div>
            <label className="text-sm font-medium">Valid Until</label>
            <Input type="date" value={validUntil} onChange={(e) => setValidUntil(e.target.value)} />
          </div>
          <div>
            <label className="text-sm font-medium">Lead (optional)</label>
            <select value={leadId} onChange={(e) => setLeadId(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 lead...</option>
              {leads.map((l: any) => (
                <option key={l.id} value={l.id}>{l.contact_name || l.company_name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="text-sm font-medium">Customer (optional)</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">VAT %</label>
            <Input type="number" value={taxPercent} onChange={(e) => setTaxPercent(parseFloat(e.target.value) || 0)} />
          </div>
        </div>

        {/* Line Items */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <label className="text-sm font-medium">Line Items</label>
            <Button size="sm" variant="outline" onClick={addItem}><Plus className="h-3.5 w-3.5 mr-1" /> Add Item</Button>
          </div>
          {items.length === 0 && (
            <p className="text-sm text-muted-foreground py-4 text-center">No items yet. Click "Add Item" to add services or products.</p>
          )}
          {items.map((item) => (
            <div key={item.id} className="flex items-start gap-3 mb-2 p-3 rounded-lg border bg-muted/20">
              <div className="flex-1 space-y-2">
                <Input
                  value={item.description}
                  onChange={(e) => updateItem(item.id, "description", e.target.value)}
                  placeholder="Service description..."
                  className="h-8 text-sm"
                />
                <div className="flex gap-2">
                  <div className="w-20">
                    <label className="text-[10px] text-muted-foreground">Qty</label>
                    <Input type="number" min="1" value={item.quantity} onChange={(e) => updateItem(item.id, "quantity", parseInt(e.target.value) || 1)} className="h-7 text-xs" />
                  </div>
                  <div className="flex-1">
                    <label className="text-[10px] text-muted-foreground">Unit Price (ZAR)</label>
                    <Input type="number" min="0" value={item.unitPrice} onChange={(e) => updateItem(item.id, "unitPrice", parseFloat(e.target.value) || 0)} className="h-7 text-xs" />
                  </div>
                  <div className="w-20">
                    <label className="text-[10px] text-muted-foreground">Discount %</label>
                    <Input type="number" min="0" max="100" value={item.discountPercent} onChange={(e) => updateItem(item.id, "discountPercent", parseFloat(e.target.value) || 0)} className="h-7 text-xs" />
                  </div>
                  <div className="w-28 text-right">
                    <label className="text-[10px] text-muted-foreground">Total</label>
                    <p className="text-sm font-medium pt-1">{formatCurrency(item.totalPrice)}</p>
                  </div>
                </div>
              </div>
              <Button variant="ghost" size="icon" className="h-8 w-8 mt-5 shrink-0" onClick={() => removeItem(item.id)}>
                <Trash2 className="h-3.5 w-3.5 text-red-500" />
              </Button>
            </div>
          ))}
        </div>

        {/* Totals */}
        <div className="border-t pt-4">
          <div className="ml-auto w-64 space-y-1 text-sm">
            <div className="flex justify-between"><span>Subtotal</span><span>{formatCurrency(subtotal)}</span></div>
            <div className="flex justify-between"><span>VAT ({taxPercent}%)</span><span>{formatCurrency(taxAmount)}</span></div>
            <div className="flex justify-between text-base font-bold border-t pt-1"><span>Total</span><span>{formatCurrency(total)}</span></div>
          </div>
        </div>

        {/* Notes & Terms */}
        <div className="grid gap-4 md:grid-cols-2">
          <div>
            <label className="text-sm font-medium">Notes</label>
            <textarea value={notes} onChange={(e) => setNotes(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="Additional notes for the client..." />
          </div>
          <div>
            <label className="text-sm font-medium">Terms & Conditions</label>
            <textarea value={terms} onChange={(e) => setTerms(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" />
          </div>
        </div>

        <div className="flex justify-end gap-3">
          <Button variant="outline" onClick={() => router.push("/proposals")}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={saving || !title}>
            {saving ? "Creating..." : <><FileText className="mr-1.5 h-4 w-4" /> Create Proposal</>}
          </Button>
        </div>
      </Card>
    </div>
  )
}
