"use client"

import { useState, useEffect, useCallback } from "react"
import { useParams, useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { ArrowLeft, FileText, CheckCircle2, Clock, User, Mail, Building2, Calendar } from "lucide-react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

export default function ProposalDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [proposal, setProposal] = useState<any>(null)
  const [statuses, setStatuses] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [signName, setSignName] = useState("")
  const [signEmail, setSignEmail] = useState("")
  const [signing, setSigning] = useState(false)

  const fetchProposal = useCallback(async () => {
    try {
      const [pRes, sRes] = await Promise.all([
        fetch(`/api/proposals/${id}`),
        fetch("/api/proposal-statuses"),
      ])
      setProposal(await pRes.json())
      setStatuses(await sRes.json())
    } catch (e) {
      console.error("Failed to load proposal", e)
    } finally {
      setLoading(false)
    }
  }, [id])

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

  const updateStatus = async (statusId: string) => {
    await fetch(`/api/proposals/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ statusId }),
    })
    fetchProposal()
  }

  const handleSign = async () => {
    if (!signName || !signEmail) return
    setSigning(true)
    try {
      const res = await fetch(`/api/proposals/${id}/sign`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: signName, email: signEmail }),
      })
      if (res.ok) fetchProposal()
    } finally {
      setSigning(false)
    }
  }

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

  if (loading) return <div className="p-8 text-center text-muted-foreground">Loading...</div>
  if (!proposal) return <div className="p-8 text-center text-muted-foreground">Proposal not found</div>

  const canSign = proposal.status_name === "Sent" || proposal.status_name === "Viewed"
  const isAccepted = proposal.status_name === "Accepted"

  return (
    <div className="space-y-6 max-w-4xl">
      <PageHeader
        title={proposal.title}
        description={`${proposal.proposal_number} · Created by ${proposal.created_by_name}`}
      >
        <Button variant="outline" size="sm" onClick={() => router.push("/proposals")}>
          <ArrowLeft className="mr-1.5 h-4 w-4" /> Back
        </Button>
      </PageHeader>

      {/* Status bar */}
      <Card className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium">Status</span>
            <Select value={proposal.status_id} onValueChange={updateStatus}>
              <SelectTrigger className="h-8 w-[150px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {statuses.map((s: any) => (
                  <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Badge variant="outline" style={{ borderColor: proposal.status_color + "40", color: proposal.status_color }}>
              {proposal.status_name}
            </Badge>
          </div>
          <div className="flex items-center gap-4 text-sm text-muted-foreground">
            <span><Calendar className="h-3.5 w-3.5 inline mr-1" />Created {formatDate(proposal.created_at)}</span>
            {proposal.valid_until && <span>Valid until {formatDate(proposal.valid_until)}</span>}
          </div>
        </div>
      </Card>

      {/* Client info */}
      {(proposal.lead_company || proposal.company_name) && (
        <Card className="p-4">
          <p className="text-sm text-muted-foreground mb-1">Client</p>
          <p className="flex items-center gap-2">
            <Building2 className="h-4 w-4 text-muted-foreground" />
            {proposal.lead_company || proposal.company_name}
          </p>
          {proposal.lead_contact && <p className="text-sm text-muted-foreground ml-6">{proposal.lead_contact}</p>}
        </Card>
      )}

      {/* Line Items */}
      <Card className="divide-y">
        <div className="px-4 py-3 font-medium text-sm">Services</div>
        {proposal.items?.length === 0 && (
          <div className="px-4 py-6 text-sm text-muted-foreground text-center">No items</div>
        )}
        {proposal.items?.map((item: any) => (
          <div key={item.id} className="flex items-center px-4 py-3 text-sm">
            <div className="flex-1">
              <p>{item.description}</p>
              <p className="text-xs text-muted-foreground">
                {item.quantity} × {formatCurrency(item.unit_price)}
                {item.discount_percent > 0 && ` (${item.discount_percent}% off)`}
              </p>
            </div>
            <p className="font-medium">{formatCurrency(item.total_price)}</p>
          </div>
        ))}
      </Card>

      {/* Totals */}
      <Card className="p-4">
        <div className="ml-auto w-64 space-y-1 text-sm">
          <div className="flex justify-between"><span>Subtotal</span><span>{formatCurrency(proposal.subtotal)}</span></div>
          <div className="flex justify-between"><span>VAT ({proposal.tax_percent}%)</span><span>{formatCurrency(proposal.tax_amount)}</span></div>
          <div className="flex justify-between text-lg font-bold border-t pt-2"><span>Total</span><span>{formatCurrency(proposal.total_amount)}</span></div>
        </div>
      </Card>

      {/* Notes & Terms */}
      {proposal.notes && (
        <Card className="p-4">
          <p className="text-sm font-medium mb-1">Notes</p>
          <p className="text-sm text-muted-foreground whitespace-pre-wrap">{proposal.notes}</p>
        </Card>
      )}
      {proposal.terms && (
        <Card className="p-4">
          <p className="text-sm font-medium mb-1">Terms & Conditions</p>
          <p className="text-sm text-muted-foreground whitespace-pre-wrap">{proposal.terms}</p>
        </Card>
      )}

      {/* E-Signature */}
      <Card className="p-6">
        <p className="text-sm font-medium mb-1">Digital Signature</p>
        <p className="text-sm text-muted-foreground mb-4">
          {isAccepted ? "This proposal has been signed and accepted." : "Sign below to accept this proposal."}
        </p>

        {proposal.signatures?.length > 0 && (
          <div className="mb-4 space-y-2">
            {proposal.signatures.map((sig: any) => (
              <div key={sig.id} className="flex items-center gap-2 text-sm">
                <CheckCircle2 className="h-4 w-4 text-emerald-500" />
                <span className="font-medium">{sig.signatory_name}</span>
                <span className="text-muted-foreground">({sig.signatory_email})</span>
                <span className="text-muted-foreground text-xs">— {new Date(sig.signed_at).toLocaleString()}</span>
              </div>
            ))}
          </div>
        )}

        {canSign && (
          <div className="space-y-3 max-w-sm">
            <Input placeholder="Full Name" value={signName} onChange={(e) => setSignName(e.target.value)} />
            <Input placeholder="Email Address" type="email" value={signEmail} onChange={(e) => setSignEmail(e.target.value)} />
            <Button onClick={handleSign} disabled={signing || !signName || !signEmail}>
              {signing ? "Signing..." : <><CheckCircle2 className="mr-1.5 h-4 w-4" /> Accept & Sign</>}
            </Button>
          </div>
        )}
      </Card>
    </div>
  )
}
