import { useEffect, useState } from "react";
import { SignaturePad } from "./SignaturePad";
import { format } from "date-fns";

interface TD29Data {
  candidate_name: string;
  date_of_training: string;
  instructor_name: string;
  instructor_reg: string;
  awarding_body: string;
  topics_covered: string[];
  policies_covered: string[];
  incident_reporting_explained: boolean;
  incident_details: string;
  candidate_signature: string;
  assessor_signature: string;
  date: string;
}

interface FormTD29Props {
  delegateName?: string;
  prefillInstructorName?: string;
  prefillInstructorReg?: string;
  onComplete: (data: TD29Data) => void;
}

const H_S_TOPICS = [
  {
    title: "Fire and evacuation",
    items: [
      "Action to take in the event of fire",
      "Location of call points",
      "Location of assembly point",
      "Identity of Fire Wardens",
    ],
  },
  {
    title: "First aid",
    items: [
      "Location of first aid box",
      "Identity of first aiders",
      "Procedure for summoning first aid",
      "Nearest hospital",
    ],
  },
  {
    title: "Welfare facilities",
    items: ["Toilets", "No smoking policy", "Breaks"],
  },
  {
    title: "Other",
    items: [
      "Emergency contact details",
      "Car parking arrangements",
      "Housekeeping",
      "Occupational health arrangements",
      "Moving vehicles",
      "Driving of a works vehicle",
    ],
  },
  {
    title: "Job safety",
    items: [
      "Risk assessments",
      "Method statements",
      "Instruct on safe systems of work",
      "Loading and unloading",
      "PPE",
      "Manual Handling",
      "Site Safety",
      "Work Force",
    ],
  },
];

const POLICIES = [
  "The Centre's H&S policy",
  "Appeals Procedure",
  "Complaints Procedure",
  "Conflict of interest",
  "Data Protection",
  "Drug & Alcohol",
  "Equality & Diversity",
  "Malpractice & Maladministration Policy",
  "Recognition of Prior Learning Policy",
  "Safeguarding Policy",
  "Privacy Policy",
  "Internal Quality assurance Policy",
  "Accident Reporting Procedure",
];

export const FormTD29 = ({
  delegateName = "",
  prefillInstructorName = "",
  prefillInstructorReg = "",
  onComplete,
}: FormTD29Props) => {
  const [formData, setFormData] = useState<TD29Data>({
    candidate_name: delegateName,
    date_of_training: format(new Date(), "dd/MM/yyyy"),
    instructor_name: prefillInstructorName,
    instructor_reg: prefillInstructorReg,
    awarding_body: "",
    topics_covered: [],
    policies_covered: [],
    incident_reporting_explained: false,
    incident_details: "",
    candidate_signature: "",
    assessor_signature: "",
    date: format(new Date(), "dd/MM/yyyy"),
  });

  // Sync candidate_name when the delegateName prop resolves later, but never
  // overwrite a value the user has actively edited.
  useEffect(() => {
    if (!delegateName) return;
    setFormData((p) => (p.candidate_name && p.candidate_name !== delegateName ? p : { ...p, candidate_name: delegateName }));
  }, [delegateName]);

  const toggleTopic = (title: string) => {
    setFormData(p => ({
      ...p,
      topics_covered: p.topics_covered.includes(title)
        ? p.topics_covered.filter(t => t !== title)
        : [...p.topics_covered, title],
    }));
  };

  const togglePolicy = (policy: string) => {
    setFormData(p => ({
      ...p,
      policies_covered: p.policies_covered.includes(policy)
        ? p.policies_covered.filter(t => t !== policy)
        : [...p.policies_covered, policy],
    }));
  };

  const allTopicsChecked = formData.topics_covered.length === H_S_TOPICS.length;
  const allPoliciesChecked = formData.policies_covered.length === POLICIES.length;
  const isValid = allTopicsChecked
    && allPoliciesChecked
    && formData.incident_reporting_explained
    && formData.candidate_signature
    && formData.candidate_name;

  const inputStyle = {
    background: "#f9fafb",
    border: "1px solid #d1d5db",
    color: "#111827",
  };

  const CheckMark = ({ checked }: { checked: boolean }) => (
    <div
      className="w-5 h-5 rounded flex items-center justify-center border-2 transition-colors shrink-0"
      style={{
        borderColor: checked ? "#16a34a" : "#d1d5db",
        background: checked ? "#16a34a" : "#ffffff",
      }}
    >
      {checked && (
        <svg className="w-3 h-3" viewBox="0 0 10 8" fill="none">
          <path d="M1 4l3 3 5-6" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      )}
    </div>
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="rounded-xl p-4" style={{ background: "#f8fafc", border: "1px solid #e2e8f0" }}>
        <h2 className="text-base font-bold" style={{ color: "#0f172a" }}>Health and Safety Induction</h2>
        <p className="text-xs mt-1" style={{ color: "#94a3b8" }}>Reference: TD-29 · Revision: 1.1</p>
      </div>

      {/* Details — matching document field layout */}
      <div className="rounded-xl overflow-hidden" style={{ border: "1px solid #e2e8f0" }}>
        {/* Training Centre row */}
        <div className="grid grid-cols-2" style={{ borderBottom: "1px solid #e2e8f0" }}>
          <div className="px-3 py-2.5" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <p className="text-xs font-semibold" style={{ color: "#374151" }}>Training Centre Name &amp; No:</p>
          </div>
          <div className="px-3 py-2.5">
            <p className="text-xs" style={{ color: "#111827" }}>Locktel Training Academy</p>
          </div>
        </div>
        {/* Name of Candidate */}
        <div className="grid grid-cols-2" style={{ borderBottom: "1px solid #e2e8f0" }}>
          <div className="px-3 py-2" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <label className="text-xs font-semibold block" style={{ color: "#374151" }}>
              Name of Candidate: <span style={{ color: "#ef4444" }}>*</span>
            </label>
          </div>
          <div className="px-3 py-1.5">
            <input
              value={formData.candidate_name}
              onChange={(e) => setFormData(p => ({ ...p, candidate_name: e.target.value }))}
              className="w-full text-xs rounded px-2 py-1.5 focus:outline-none focus:ring-1"
              style={inputStyle}
              placeholder="Candidate name"
            />
          </div>
        </div>
        {/* Date of Training */}
        <div className="grid grid-cols-2" style={{ borderBottom: "1px solid #e2e8f0" }}>
          <div className="px-3 py-2" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <label className="text-xs font-semibold block" style={{ color: "#374151" }}>Date of Training:</label>
          </div>
          <div className="px-3 py-1.5">
            <input
              value={formData.date_of_training}
              onChange={(e) => setFormData(p => ({ ...p, date_of_training: e.target.value }))}
              className="w-full text-xs rounded px-2 py-1.5 focus:outline-none focus:ring-1"
              style={inputStyle}
            />
          </div>
        </div>
        {/* Name of Instructor/Assessor */}
        <div className="grid grid-cols-2" style={{ borderBottom: "1px solid #e2e8f0" }}>
          <div className="px-3 py-2" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <label className="text-xs font-semibold block" style={{ color: "#374151" }}>Name of Instructor/Assessor:</label>
          </div>
          <div className="px-3 py-1.5">
            <input
              value={formData.instructor_name}
              onChange={(e) => setFormData(p => ({ ...p, instructor_name: e.target.value }))}
              className="w-full text-xs rounded px-2 py-1.5 focus:outline-none focus:ring-1"
              style={inputStyle}
              placeholder="Instructor name"
            />
          </div>
        </div>
        {/* Instructor/Assessor Reg No */}
        <div className="grid grid-cols-2" style={{ borderBottom: "1px solid #e2e8f0" }}>
          <div className="px-3 py-2" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <label className="text-xs font-semibold block" style={{ color: "#374151" }}>Instructor/Assessor Reg No:</label>
          </div>
          <div className="px-3 py-1.5">
            <input
              value={formData.instructor_reg}
              onChange={(e) => setFormData(p => ({ ...p, instructor_reg: e.target.value }))}
              className="w-full text-xs rounded px-2 py-1.5 focus:outline-none focus:ring-1"
              style={inputStyle}
              placeholder="Registration number"
            />
          </div>
        </div>
        {/* Name of awarding body */}
        <div className="grid grid-cols-2">
          <div className="px-3 py-2" style={{ background: "#f8fafc", borderRight: "1px solid #e2e8f0" }}>
            <label className="text-xs font-semibold block" style={{ color: "#374151" }}>Name of awarding body:</label>
          </div>
          <div className="px-3 py-1.5">
            <input
              value={formData.awarding_body}
              onChange={(e) => setFormData(p => ({ ...p, awarding_body: e.target.value }))}
              className="w-full text-xs rounded px-2 py-1.5 focus:outline-none focus:ring-1"
              style={inputStyle}
              placeholder="Awarding body name"
            />
          </div>
        </div>
      </div>

      {/* Topics — 3-column table matching document: Topic | Cover these issues | ✓ when done */}
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <label className="text-sm font-semibold" style={{ color: "#374151" }}>
            Health &amp; Safety Topics <span style={{ color: "#ef4444" }}>*</span>
          </label>
          <span className="text-xs" style={{ color: "#64748b" }}>
            {formData.topics_covered.length} / {H_S_TOPICS.length} ✓ when done
          </span>
        </div>
        <div className="rounded-xl overflow-hidden" style={{ border: "1px solid #e2e8f0" }}>
          {/* Table header */}
          <div className="grid" style={{ gridTemplateColumns: "160px 1fr 80px", background: "#f1f5f9", borderBottom: "1px solid #e2e8f0" }}>
            <div className="px-3 py-2.5" style={{ borderRight: "1px solid #e2e8f0" }}>
              <span className="text-xs font-bold" style={{ color: "#374151" }}>Topic</span>
            </div>
            <div className="px-3 py-2.5" style={{ borderRight: "1px solid #e2e8f0" }}>
              <span className="text-xs font-bold" style={{ color: "#374151" }}>Cover these issues</span>
            </div>
            <div className="px-3 py-2.5 flex items-center justify-center">
              <span className="text-xs font-bold text-center" style={{ color: "#374151" }}>✓ when done</span>
            </div>
          </div>
          {/* Topic rows */}
          {H_S_TOPICS.map((section, i) => {
            const checked = formData.topics_covered.includes(section.title);
            return (
              <div
                key={section.title}
                className="grid cursor-pointer transition-colors"
                style={{
                  gridTemplateColumns: "160px 1fr 80px",
                  background: checked ? "#f0fdf4" : "#ffffff",
                  borderBottom: i < H_S_TOPICS.length - 1 ? "1px solid #e2e8f0" : "none",
                }}
                onClick={() => toggleTopic(section.title)}
              >
                <div className="px-3 py-3 flex items-start" style={{ borderRight: "1px solid #e2e8f0" }}>
                  <span className="text-xs font-semibold capitalize leading-snug" style={{ color: "#0f172a" }}>
                    {section.title}
                  </span>
                </div>
                <div className="px-3 py-3" style={{ borderRight: "1px solid #e2e8f0" }}>
                  <ul className="space-y-1">
                    {section.items.map(item => (
                      <li key={item} className="text-xs leading-snug flex items-start gap-1.5" style={{ color: "#374151" }}>
                        <span className="mt-0.5" style={{ color: "#9ca3af" }}>•</span>
                        {item}
                      </li>
                    ))}
                  </ul>
                </div>
                <div className="px-3 py-3 flex items-center justify-center">
                  <CheckMark checked={checked} />
                </div>
              </div>
            );
          })}
        </div>
        {!allTopicsChecked && (
          <p className="text-xs" style={{ color: "#d97706" }}>All topics must be confirmed before submitting.</p>
        )}
      </div>

      {/* Incident reporting */}
      <div className="rounded-xl overflow-hidden" style={{ border: "1px solid #e2e8f0" }}>
        <div className="px-4 py-2.5" style={{ background: "#f1f5f9", borderBottom: "1px solid #e2e8f0" }}>
          <p className="text-xs font-bold" style={{ color: "#374151" }}>
            2. Incident reporting <span style={{ color: "#ef4444" }}>*</span>
          </p>
        </div>
        <div className="px-4 py-3 space-y-3">
          <div
            className="flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-colors"
            style={{
              background: formData.incident_reporting_explained ? "#f0fdf4" : "#ffffff",
              border: "1px solid #f3f4f6",
            }}
            onClick={() =>
              setFormData((p) => ({ ...p, incident_reporting_explained: !p.incident_reporting_explained }))
            }
          >
            <div
              className="w-4 h-4 rounded shrink-0 mt-0.5 flex items-center justify-center border-2 transition-colors"
              style={{
                borderColor: formData.incident_reporting_explained ? "#16a34a" : "#d1d5db",
                background: formData.incident_reporting_explained ? "#16a34a" : "#ffffff",
              }}
            >
              {formData.incident_reporting_explained && (
                <svg className="w-2.5 h-2.5" viewBox="0 0 10 8" fill="none">
                  <path d="M1 4l3 3 5-6" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              )}
            </div>
            <span className="text-sm leading-snug" style={{ color: "#111827" }}>
              Candidate has been informed of the incident reporting procedure (who to notify, where to find the
              accident book, and what to do in the event of an accident, near-miss, or dangerous occurrence).
            </span>
          </div>

          <div className="space-y-1.5">
            <label className="text-xs font-medium block" style={{ color: "#374151" }}>
              Details of any incidents during this session (optional)
            </label>
            <textarea
              value={formData.incident_details}
              onChange={(e) => setFormData((p) => ({ ...p, incident_details: e.target.value }))}
              rows={3}
              placeholder="Leave blank if no incidents occurred."
              className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 resize-none"
              style={{
                background: "#f9fafb",
                border: "1px solid #d1d5db",
                color: "#111827",
              }}
            />
          </div>
        </div>
      </div>

      {/* Centre's policy and procedures */}
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <label className="text-sm font-semibold" style={{ color: "#374151" }}>
            3. Centre&rsquo;s policy and procedures <span style={{ color: "#ef4444" }}>*</span>
          </label>
          <span className="text-xs" style={{ color: "#64748b" }}>
            {formData.policies_covered.length} / {POLICIES.length}
          </span>
        </div>
        <p className="text-xs" style={{ color: "#6b7280" }}>Explain and show the Candidates:</p>
        <div className="rounded-xl overflow-hidden" style={{ border: "1px solid #e2e8f0" }}>
          {POLICIES.map((policy, idx) => {
            const checked = formData.policies_covered.includes(policy);
            return (
              <div
                key={policy}
                className="flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors"
                style={{
                  background: checked ? "#f0fdf4" : "#ffffff",
                  borderTop: idx > 0 ? "1px solid #f3f4f6" : "none",
                }}
                onClick={() => togglePolicy(policy)}
              >
                <CheckMark checked={checked} />
                <span className="text-sm" style={{ color: "#111827" }}>{policy}</span>
              </div>
            );
          })}
        </div>
        {!allPoliciesChecked && (
          <p className="text-xs" style={{ color: "#d97706" }}>All policies must be confirmed before submitting.</p>
        )}
      </div>

      {/* 4. Signatures */}
      <div className="space-y-4 pt-5" style={{ borderTop: "1px solid #e5e7eb" }}>
        <p className="text-xs font-semibold" style={{ color: "#374151" }}>4. Signatures</p>
        <SignaturePad
          label={`Candidates Signature * (Date of Induction: ${formData.date})`}
          value={formData.candidate_signature}
          onChange={(sig) => setFormData(p => ({ ...p, candidate_signature: sig }))}
        />
        <SignaturePad
          label={`Assessor/Instructor Signature (Date of Induction: ${formData.date})`}
          value={formData.assessor_signature}
          onChange={(sig) => setFormData(p => ({ ...p, assessor_signature: sig }))}
        />
      </div>

      <button
        className="w-full flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-semibold"
        disabled={!isValid}
        onClick={() => isValid && onComplete(formData)}
        style={{
          background: isValid ? "#f97316" : "#e5e7eb",
          color: isValid ? "#ffffff" : "#9ca3af",
          cursor: isValid ? "pointer" : "not-allowed",
          border: "none",
        }}
      >
        Submit All Forms
      </button>
      {!isValid && (
        <p className="text-xs text-center" style={{ color: "#9ca3af" }}>
          Please confirm all topics, policies, and sign before submitting.
        </p>
      )}
    </div>
  );
};
