"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"

interface CompanyData {
  companyName: string
  companyEmail: string
  companyPhone: string
  companyWebsite: string
  companyAddress: string
}

export function CompanySettingsForm() {
  const [data, setData] = useState<CompanyData>({
    companyName: "",
    companyEmail: "",
    companyPhone: "",
    companyWebsite: "",
    companyAddress: "",
  })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch("/api/settings/company")
        if (res.ok) {
          const json = await res.json()
          setData(json)
        }
      } catch {
        console.warn("Failed to load company settings")
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  async function handleSave() {
    setSaving(true)
    try {
      const res = await fetch("/api/settings/company", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        toast.success("Company settings saved")
      } else {
        toast.error("Failed to save company settings")
      }
    } catch {
      console.warn("Failed to save company settings")
      toast.error("Failed to save company settings")
    } finally {
      setSaving(false)
    }
  }

  function update(field: keyof CompanyData, value: string) {
    setData((prev) => ({ ...prev, [field]: value }))
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Company Settings</CardTitle>
        <CardDescription>
          Manage your company information and branding.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="company-name">Company Name</Label>
            <Input id="company-name" disabled={loading} value={data.companyName} onChange={(e) => update("companyName", e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="company-email">Company Email</Label>
            <Input id="company-email" type="email" disabled={loading} value={data.companyEmail} onChange={(e) => update("companyEmail", e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="company-phone">Phone</Label>
            <Input id="company-phone" disabled={loading} value={data.companyPhone} onChange={(e) => update("companyPhone", e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="company-website">Website</Label>
            <Input id="company-website" disabled={loading} value={data.companyWebsite} onChange={(e) => update("companyWebsite", e.target.value)} />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="company-address">Address</Label>
            <Input id="company-address" disabled={loading} value={data.companyAddress} onChange={(e) => update("companyAddress", e.target.value)} />
          </div>
        </div>
        <form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
          <div className="flex justify-end pt-4">
            <Button type="submit" disabled={loading || saving}>
              {saving ? "Saving..." : "Save Changes"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
