"use client"

import { useState, useEffect, useCallback } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Check, X, Pencil, Save } from "lucide-react"

interface FieldDef {
  id: string
  entity_type: string
  field_key: string
  field_label: string
  field_type: string
  options: string[] | null
  placeholder: string | null
  default_value: string | null
  section: string | null
  is_required: boolean
  sort_order: number
}

interface CustomFieldsSectionProps {
  entityType: string
  customFields?: Record<string, any>
  entityId: string
  apiEndpoint: string
  title?: string
}

export function CustomFieldsSection({ entityType, customFields = {}, entityId, apiEndpoint, title = "Custom Fields" }: CustomFieldsSectionProps) {
  const [definitions, setDefinitions] = useState<FieldDef[]>([])
  const [editing, setEditing] = useState(false)
  const [values, setValues] = useState<Record<string, any>>(customFields)
  const [saving, setSaving] = useState(false)
  const [loading, setLoading] = useState(true)

  const loadDefinitions = useCallback(async () => {
    try {
      const res = await fetch(`/api/custom-fields?entityType=${entityType}`)
      if (res.ok) setDefinitions(await res.json())
    } catch { /* ignore */ }
    setLoading(false)
  }, [entityType])

  useEffect(() => { loadDefinitions() }, [loadDefinitions])
  useEffect(() => { setValues(customFields) }, [customFields])

  if (loading || definitions.length === 0) return null

  const grouped = definitions.reduce<Record<string, FieldDef[]>>((acc, f) => {
    const section = f.section || "Other"
    if (!acc[section]) acc[section] = []
    acc[section].push(f)
    return acc
  }, {})

  async function handleSave() {
    setSaving(true)
    try {
      await fetch(apiEndpoint, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ customFields: values }),
      })
      setEditing(false)
    } catch { /* ignore */ }
    setSaving(false)
  }

  function renderField(field: FieldDef) {
    const key = field.field_key
    const val = values?.[key]

    if (editing) {
      return renderEditField(field, key, val)
    }

    if (val === undefined || val === null || val === "") return null

    return renderDisplayField(field, key, val)
  }

  function renderDisplayField(field: FieldDef, key: string, val: any) {
    let display: React.ReactNode = String(val)

    switch (field.field_type) {
      case "boolean":
        display = val ? <Badge variant="default" className="bg-emerald-500"><Check className="h-3 w-3 mr-1" />Yes</Badge> : <Badge variant="secondary"><X className="h-3 w-3 mr-1" />No</Badge>
        break
      case "select":
        display = <Badge variant="outline">{String(val)}</Badge>
        break
      case "multi_select":
        const arr = Array.isArray(val) ? val : [val]
        display = <div className="flex flex-wrap gap-1">{arr.map((v: string) => <Badge key={v} variant="secondary">{v}</Badge>)}</div>
        break
      case "url":
        display = <a href={String(val)} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline truncate block max-w-[200px]">{String(val)}</a>
        break
      case "date":
        display = new Date(val).toLocaleDateString()
        break
    }

    return (
      <div key={key} className="space-y-0.5">
        <p className="text-xs text-muted-foreground">{field.field_label}</p>
        <div className="text-sm font-medium">{display}</div>
      </div>
    )
  }

  function renderEditField(field: FieldDef, key: string, val: any) {
    const setVal = (v: any) => setValues(prev => ({ ...prev, [key]: v }))

    switch (field.field_type) {
      case "text":
      case "email":
      case "phone":
      case "url":
        return (
          <div key={key}>
            <label className="text-xs font-medium mb-1 block">{field.field_label}</label>
            <Input value={val || ""} onChange={e => setVal(e.target.value)} placeholder={field.placeholder || ""} />
          </div>
        )
      case "number":
        return (
          <div key={key}>
            <label className="text-xs font-medium mb-1 block">{field.field_label}</label>
            <Input type="number" value={val || ""} onChange={e => setVal(e.target.value ? Number(e.target.value) : null)} placeholder={field.placeholder || ""} />
          </div>
        )
      case "date":
        return (
          <div key={key}>
            <label className="text-xs font-medium mb-1 block">{field.field_label}</label>
            <Input type="date" value={val || ""} onChange={e => setVal(e.target.value)} />
          </div>
        )
      case "boolean":
        return (
          <div key={key} className="flex items-center gap-2">
            <Switch checked={!!val} onCheckedChange={setVal} />
            <label className="text-sm">{field.field_label}</label>
          </div>
        )
      case "select":
        return (
          <div key={key}>
            <label className="text-xs font-medium mb-1 block">{field.field_label}</label>
            <Select value={val || ""} onValueChange={setVal}>
              <SelectTrigger>
                <SelectValue placeholder="Select..." />
              </SelectTrigger>
              <SelectContent>
                {(field.options || []).map(o => <SelectItem key={o} value={o}>{o}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
        )
      case "multi_select":
        return (
          <div key={key}>
            <label className="text-xs font-medium mb-1 block">{field.field_label}</label>
            <div className="flex flex-wrap gap-1">
              {(field.options || []).map(o => (
                <button
                  key={o}
                  onClick={() => {
                    const current = Array.isArray(val) ? val : []
                    setVal(current.includes(o) ? current.filter((v: string) => v !== o) : [...current, o])
                  }}
                  className={`px-2 py-1 text-xs rounded-full border transition-colors ${(Array.isArray(val) && val.includes(o)) ? "bg-primary text-primary-foreground border-primary" : "bg-background hover:bg-muted"}`}
                >
                  {o}
                </button>
              ))}
            </div>
          </div>
        )
      default:
        return null
    }
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="text-base">{title}</CardTitle>
        {editing ? (
          <div className="flex gap-1">
            <Button size="sm" variant="ghost" onClick={() => { setEditing(false); setValues(customFields) }}>
              <X className="h-4 w-4" />
            </Button>
            <Button size="sm" onClick={handleSave} disabled={saving}>
              <Save className="h-4 w-4 mr-1" />
              {saving ? "Saving..." : "Save"}
            </Button>
          </div>
        ) : (
          <Button size="sm" variant="ghost" onClick={() => setEditing(true)}>
            <Pencil className="h-4 w-4 mr-1" />Edit
          </Button>
        )}
      </CardHeader>
      <CardContent>
        {Object.entries(grouped).map(([section, sectionFields]) => {
          const rendered = sectionFields.map(renderField).filter(Boolean)
          if (rendered.length === 0 && !editing) return null
          return (
            <div key={section} className={section !== Object.keys(grouped)[0] ? "mt-4 pt-4 border-t" : ""}>
              <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">{section}</h4>
              <div className="grid gap-3 sm:grid-cols-2">
                {rendered}
              </div>
            </div>
          )
        })}
        {definitions.length > 0 && !Object.values(grouped).some(sf => sf.some(f => {
          const v = values?.[f.field_key]
          return v !== undefined && v !== null && v !== ""
        })) && !editing && (
          <p className="text-sm text-muted-foreground">No custom fields set yet.</p>
        )}
      </CardContent>
    </Card>
  )
}
