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

interface TD07Data {
  assessor_name: string;
  assessor_number: string;
  candidate_name: string;
  employer: string;
  date_time: string;
  start_date: string;
  topics_covered: string[];
  additional_notes: string;
  candidate_signature: string;
  assessor_signature: string;
  date: string;
}

interface FormTD07Props {
  delegateName?: string;
  onComplete: (data: TD07Data) => void;
}

const INDUCTION_TOPICS = [
  "Assessor and Candidate confirm that the relevant pre-assessment training courses have been successfully completed as per the Awarding Body requirements",
  "Candidate is made aware of the Training Provider's Policies and how to access them if required.",
  "Candidate is aware of the appeals and disputes procedure",
  "Candidate is aware of the complaint's procedure",
  "Candidate is aware of the Malpractice and Maladministration policy",
  "Candidate is aware of the equal opportunity policy",
  "Candidate is aware of the qualification standards",
  "Candidate is aware of the assessment process",
  "Candidate is aware of the Assessor, Internal Quality and External Quality Assurer and their roles",
  "Candidate is aware of the need to keep records up to date and signed",
  "Candidate is aware of the opportunity to give and receive feedback",
  "Assessor and Candidate have completed the assessment plan",
  "Candidate has Signed into the Risk Assessment",
  "Candidate is aware that personal data will be shared with Data Processors (awarding Bodies)",
];

export const FormTD07 = ({ delegateName = "", onComplete }: FormTD07Props) => {
  const [formData, setFormData] = useState<TD07Data>({
    assessor_name: "",
    assessor_number: "",
    candidate_name: delegateName,
    employer: "",
    date_time: format(new Date(), "dd/MM/yyyy HH:mm"),
    start_date: format(new Date(), "dd/MM/yyyy"),
    topics_covered: [],
    additional_notes: "",
    candidate_signature: "",
    assessor_signature: "",
    date: format(new Date(), "dd/MM/yyyy"),
  });

  // The delegate name resolves asynchronously; useState only honours its
  // initialiser on the first render, so sync candidate_name whenever the
  // prop changes — but never overwrite a value the user has already typed.
  useEffect(() => {
    if (!delegateName) return;
    setFormData((p) => (p.candidate_name && p.candidate_name !== delegateName ? p : { ...p, candidate_name: delegateName }));
  }, [delegateName]);

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

  const allTopicsChecked = formData.topics_covered.length === INDUCTION_TOPICS.length;
  const isValid = allTopicsChecked && formData.candidate_signature && formData.employer;

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

  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" }}>CANDIDATE INDUCTION</h2>
        <p className="text-sm mt-1" style={{ color: "#64748b" }}>
          This is to confirm that the Candidate has been inducted into the Training Provider policies and procedures
        </p>
        <div className="mt-2 flex flex-wrap gap-x-6 gap-y-1">
          <p className="text-xs" style={{ color: "#94a3b8" }}>
            <span className="font-medium" style={{ color: "#64748b" }}>Training Provider Name:</span> Locktel Academy
          </p>
          <p className="text-xs" style={{ color: "#94a3b8" }}>
            <span className="font-medium" style={{ color: "#64748b" }}>Training Provider Number:</span> 1105
          </p>
        </div>
        <p className="text-xs mt-1" style={{ color: "#94a3b8" }}>Reference: TD-07 · Revision: 1.2</p>
      </div>

      {/* Details */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>
            Assessor / Instructor Name
          </label>
          <input
            value={formData.assessor_name}
            onChange={(e) => setFormData(p => ({ ...p, assessor_name: e.target.value }))}
            placeholder="Assessor name"
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>
            Assessor / Instructor Number
          </label>
          <input
            value={formData.assessor_number}
            onChange={(e) => setFormData(p => ({ ...p, assessor_number: e.target.value }))}
            placeholder="Assessor number"
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>
            Candidate Name <span style={{ color: "#ef4444" }}>*</span>
          </label>
          <input
            value={formData.candidate_name}
            onChange={(e) => setFormData(p => ({ ...p, candidate_name: e.target.value }))}
            placeholder="Candidate name"
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>
            Employer <span style={{ color: "#ef4444" }}>*</span>
          </label>
          <input
            value={formData.employer}
            onChange={(e) => setFormData(p => ({ ...p, employer: e.target.value }))}
            placeholder="Employer name"
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>Date &amp; Time</label>
          <input
            value={formData.date_time}
            onChange={(e) => setFormData(p => ({ ...p, date_time: e.target.value }))}
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
        <div className="space-y-1.5">
          <label className="text-sm font-medium block" style={{ color: "#374151" }}>Start date for assessments</label>
          <input
            value={formData.start_date}
            onChange={(e) => setFormData(p => ({ ...p, start_date: e.target.value }))}
            className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2"
            style={inputStyle}
          />
        </div>
      </div>

      {/* Induction Topics */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <label className="text-sm font-semibold block" style={{ color: "#374151" }}>
            Induction Topics <span style={{ color: "#ef4444" }}>*</span>
          </label>
          <span className="text-xs" style={{ color: "#64748b" }}>
            {formData.topics_covered.length} / {INDUCTION_TOPICS.length} covered
          </span>
        </div>
        <div className="rounded-xl overflow-hidden" style={{ border: "1px solid #e5e7eb" }}>
          {INDUCTION_TOPICS.map((topic, i) => {
            const checked = formData.topics_covered.includes(topic);
            return (
              <div
                key={i}
                className="flex items-start gap-3 p-3 cursor-pointer transition-colors"
                style={{
                  background: checked ? "#f0fdf4" : "#ffffff",
                  borderBottom: i < INDUCTION_TOPICS.length - 1 ? "1px solid #f3f4f6" : "none",
                }}
                onClick={() => toggleTopic(topic)}
              >
                <div
                  className="w-4 h-4 rounded shrink-0 mt-0.5 flex items-center justify-center border-2 transition-colors"
                  style={{
                    borderColor: checked ? "#16a34a" : "#d1d5db",
                    background: checked ? "#16a34a" : "#ffffff",
                  }}
                >
                  {checked && (
                    <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" }}>{topic}</span>
              </div>
            );
          })}
        </div>
        {!allTopicsChecked && (
          <p className="text-xs" style={{ color: "#d97706" }}>All 14 topics must be confirmed before submitting.</p>
        )}
      </div>

      {/* Additional Notes */}
      <div className="space-y-1.5">
        <label className="text-sm font-medium block" style={{ color: "#374151" }}>
          Additional notes about induction if required
        </label>
        <textarea
          value={formData.additional_notes}
          onChange={(e) => setFormData(p => ({ ...p, additional_notes: e.target.value }))}
          rows={3}
          className="w-full rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 resize-none"
          style={inputStyle}
          placeholder="Any additional notes..."
        />
      </div>

      {/* Signatures */}
      <div className="space-y-4 pt-5" style={{ borderTop: "1px solid #e5e7eb" }}>
        <p className="text-xs" style={{ color: "#64748b" }}>
          After completion of the section above, this form should be signed and dated by both the Candidate and the Assessor to act as an agreement between both parties that all items have been covered.
        </p>
        <SignaturePad
          label={`Candidate Signature * (Date: ${formData.date})`}
          value={formData.candidate_signature}
          onChange={(sig) => setFormData(p => ({ ...p, candidate_signature: sig }))}
        />
        <SignaturePad
          label={`Assessor Signature (Date: ${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 transition-opacity"
        disabled={!isValid}
        onClick={() => isValid && onComplete(formData)}
        style={{
          background: isValid ? "#f97316" : "#e5e7eb",
          color: isValid ? "#ffffff" : "#9ca3af",
          cursor: isValid ? "pointer" : "not-allowed",
          border: "none",
        }}
      >
        Continue to Health &amp; Safety <ArrowRight className="w-4 h-4" />
      </button>
    </div>
  );
};
