"use client";
import { useEffect, useRef } from "react";
import flatpickr from "flatpickr";
import "flatpickr/dist/flatpickr.css";

// FIX 1: Added label, value, onChange, required, disabled props — was completely hardcoded
// FIX 2: id derived from label — was hardcoded "datepicker", clashed with CommonDateRange
// FIX 3: Removed <style jsx global> — requires @types/styled-jsx, breaks in Next.js App Router
// FIX 4: Sync flatpickr when parent changes value

interface CommonDateProps {
  label?: string;
  value?: string;
  onChange?: (value: string) => void;
  required?: boolean;
  disabled?: boolean;
  placeholder?: string;
  dateFormat?: string;
}

export default function CommonDate({
  label = "Date", value, onChange,
  required = false, disabled = false,
  placeholder = "dd/mm/yyyy", dateFormat = "d/m/Y",
}: CommonDateProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const fpRef    = useRef<ReturnType<typeof flatpickr> | null>(null);
  const fieldId  = `datepicker-${label.toLowerCase().replace(/\s+/g, "-")}`;

  useEffect(() => {
    if (!inputRef.current) return;
    fpRef.current = flatpickr(inputRef.current, {
      disableMobile: true,
      dateFormat,
      defaultDate: value,
      onChange: ([date]) => {
        if (!date) return;
        const d = String(date.getDate()).padStart(2, "0");
        const m = String(date.getMonth() + 1).padStart(2, "0");
        onChange?.(`${d}/${m}/${date.getFullYear()}`);
      },
    });
    return () => { (fpRef.current as any)?.destroy?.(); };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!fpRef.current || !value) return;
    (fpRef.current as any).setDate?.(value, false);
  }, [value]);

  return (
    <div>
      <label className="form-label" htmlFor={fieldId}>{label}</label>
      <input
        ref={inputRef}
        className="form-control datetimepicker"
        id={fieldId}
        type="text"
        placeholder={placeholder}
        required={required}
        disabled={disabled}
        readOnly
      />
    </div>
  );
}
