"use client";

import { useMemo } from "react";
import { CheckCircle2, CircleDashed } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import type { SuratData, SuratField, SuratTemplate } from "@/lib/surat/types";
import { isFieldSection, isIdentitySection, isTableBlock } from "@/lib/surat/types";

export function SuratDataForm({
  template,
  value,
  onChange,
  idPrefix = "surat",
  className,
}: {
  template: SuratTemplate;
  value: SuratData;
  onChange: (next: SuratData) => void;
  idPrefix?: string;
  className?: string;
}) {
  const groups = useMemo(() => {
    const fieldsByKey = new Map(template.fields.map((field) => [field.key, field]));
    const used = new Set<string>();
    const result: Array<{ title: string; note?: string; fields: SuratField[] }> = [];

    for (const section of template.sections) {
      if (!isFieldSection(section)) continue;
      const fields = section.fields
        .map((key) => fieldsByKey.get(key))
        .filter((field): field is SuratField => Boolean(field))
        .filter((field) => {
          if (used.has(field.key)) return false;
          used.add(field.key);
          return true;
        });
      if (fields.length) {
        result.push({
          title: section.title ?? "Data Surat",
          note: section.note,
          fields,
        });
      }
    }

    const remaining = template.fields.filter((field) => !used.has(field.key));
    if (remaining.length) {
      result.push({ title: "Data Tambahan", fields: remaining });
    }
    return result;
  }, [template]);

  const total = template.fields.length;
  const filled = template.fields.filter((field) => value[field.key]?.trim()).length;
  const percent = total ? Math.round((filled / total) * 100) : 100;

  function update(key: string, next: string) {
    onChange({ ...value, [key]: next });
  }

  if (!template.fields.length) {
    return (
      <div className="rounded-xl border border-dashed p-4 text-sm text-muted-foreground">
        Surat ini tidak memerlukan data tambahan. Data pemohon diambil otomatis dari
        data kependudukan.
      </div>
    );
  }

  return (
    <div className={cn("space-y-5", className)}>
      <div className="flex items-center justify-between gap-3 rounded-xl border border-border bg-muted/40 px-4 py-3">
        <div>
          <p className="text-sm font-semibold text-foreground">{template.nama}</p>
          <p className="text-xs text-muted-foreground">{template.ringkasan}</p>
        </div>
        <div className="shrink-0 text-right">
          <div className="flex items-center justify-end gap-1.5 text-xs font-medium">
            {filled === total ? (
              <CheckCircle2 className="h-3.5 w-3.5 text-primary" />
            ) : (
              <CircleDashed className="h-3.5 w-3.5 text-muted-foreground" />
            )}
            {filled}/{total} terisi
          </div>
          <div className="mt-1 h-1.5 w-24 overflow-hidden rounded-full bg-border">
            <div
              className="h-full rounded-full bg-primary transition-all"
              style={{ width: `${percent}%` }}
            />
          </div>
        </div>
      </div>

      {groups.map((group, index) => (
        <fieldset key={`${group.title}-${index}`} className="space-y-3">
          <legend className="w-full border-b border-dashed border-border pb-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
            {group.title}
          </legend>
          {group.note && <p className="text-xs text-muted-foreground">{group.note}</p>}
          <div className="grid gap-3 sm:grid-cols-2">
            {group.fields.map((field) => {
              const id = `${idPrefix}-${field.key}`;
              const span = field.span ?? (field.type === "textarea" ? 2 : 1);
              return (
                <div
                  key={field.key}
                  className={cn("space-y-1.5", span === 2 && "sm:col-span-2")}
                >
                  <Label htmlFor={id} className="text-xs">
                    {field.label}
                    {field.required && <span className="text-destructive"> *</span>}
                  </Label>
                  {field.type === "textarea" ? (
                    <Textarea
                      id={id}
                      rows={2}
                      required={field.required}
                      value={value[field.key] ?? ""}
                      placeholder={field.placeholder ?? field.label}
                      onChange={(event) => update(field.key, event.target.value)}
                    />
                  ) : field.type === "select" ? (
                    <Select
                      id={id}
                      required={field.required}
                      value={value[field.key] ?? ""}
                      onChange={(event) => update(field.key, event.target.value)}
                    >
                      <option value="">Pilih {field.label.toLowerCase()}</option>
                      {(field.options ?? []).map((option) => (
                        <option key={option} value={option}>
                          {option}
                        </option>
                      ))}
                    </Select>
                  ) : (
                    <Input
                      id={id}
                      type={field.type ?? "text"}
                      required={field.required}
                      value={value[field.key] ?? ""}
                      placeholder={field.placeholder ?? field.label}
                      onChange={(event) => update(field.key, event.target.value)}
                    />
                  )}
                  {field.help && (
                    <p className="text-[11px] text-muted-foreground">{field.help}</p>
                  )}
                </div>
              );
            })}
          </div>
        </fieldset>
      ))}

      {template.catatan?.length ? (
        <div className="rounded-lg border border-amber-200 bg-amber-50/70 p-3 text-[11px] leading-relaxed text-amber-900">
          {template.catatan.map((note) => (
            <p key={note}>{note}</p>
          ))}
        </div>
      ) : null}
    </div>
  );
}

export function sectionCount(template: SuratTemplate) {
  return template.sections.filter(
    (section) => isIdentitySection(section) || isFieldSection(section) || isTableBlock(section),
  ).length;
}
