"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { calcDuration, JOB_CATEGORY_LABELS } from "@/lib/utils";
import { ChevronLeft, ChevronRight, Save, Send } from "lucide-react";

type FormData = {
  date: string;
  jobNo: string;
  customerName: string;
  customerAddress: string;
  contactPerson: string;
  telephone: string;
  fax: string;
  customerEmail: string;
  jobCategory: string;
  equipment: string;
  make: string;
  model: string;
  dateInstalled: string;
  serialNo: string;
  natureOfIntervention: string;
  actionTaken: string;
  workCompleted: boolean;
  workNotCompletedDetails: string;
  tech1Name: string;
  tech1TimeIn: string;
  tech1TimeOut: string;
  tech2Name: string;
  tech2TimeIn: string;
  tech2TimeOut: string;
  tech3Name: string;
  tech3TimeIn: string;
  tech3TimeOut: string;
  equipmentUnderWarranty: string;
  techniciansReport: string;
  comments: string;
  customerSignName: string;
  customerSignTitle: string;
  technetSignName: string;
  technetSignTitle: string;
};

const EMPTY: FormData = {
  date: new Date().toISOString().slice(0, 10),
  jobNo: "",
  customerName: "",
  customerAddress: "",
  contactPerson: "",
  telephone: "",
  fax: "",
  customerEmail: "",
  jobCategory: "",
  equipment: "",
  make: "",
  model: "",
  dateInstalled: "",
  serialNo: "",
  natureOfIntervention: "",
  actionTaken: "",
  workCompleted: true,
  workNotCompletedDetails: "",
  tech1Name: "",
  tech1TimeIn: "",
  tech1TimeOut: "",
  tech2Name: "",
  tech2TimeIn: "",
  tech2TimeOut: "",
  tech3Name: "",
  tech3TimeIn: "",
  tech3TimeOut: "",
  equipmentUnderWarranty: "",
  techniciansReport: "",
  comments: "",
  customerSignName: "",
  customerSignTitle: "",
  technetSignName: "",
  technetSignTitle: "",
};

const STEPS = ["Header", "Customer", "Job & Equipment", "Intervention", "Technicians", "Report & Sign"];

export function InterventionForm({ initialData, reportId }: { initialData?: Partial<FormData>; reportId?: string }) {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [form, setForm] = useState<FormData>({ ...EMPTY, ...initialData });
  const [saving, setSaving] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  function set(field: keyof FormData, value: string | boolean) {
    setForm((f) => ({ ...f, [field]: value }));
  }

  async function saveReport(): Promise<string | null> {
    setSaving(true);
    setError("");
    try {
      const payload = {
        ...form,
        tech1Duration: calcDuration(form.tech1TimeIn, form.tech1TimeOut),
        tech2Duration: calcDuration(form.tech2TimeIn, form.tech2TimeOut),
        tech3Duration: calcDuration(form.tech3TimeIn, form.tech3TimeOut),
        jobCategory: form.jobCategory || null,
        equipmentUnderWarranty: form.equipmentUnderWarranty || null,
      };

      if (reportId) {
        await fetch(`/api/reports/${reportId}`, { method: "PATCH", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
        return reportId;
      } else {
        const res = await fetch("/api/reports", { method: "POST", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
        const data = await res.json();
        return data.id;
      }
    } catch {
      setError("Failed to save. Please try again.");
      return null;
    } finally {
      setSaving(false);
    }
  }

  async function handleSaveDraft() {
    const id = await saveReport();
    if (id && !reportId) {
      router.replace(`/reports/${id}`);
    }
  }

  async function handleSubmit() {
    const id = await saveReport();
    if (!id) return;
    setSubmitting(true);
    try {
      await fetch(`/api/reports/${id}/submit`, { method: "POST" });
      router.push("/dashboard");
    } catch {
      setError("Failed to submit.");
    } finally {
      setSubmitting(false);
    }
  }

  const inputCls = "w-full border border-gray-300 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white";
  const labelCls = "block text-sm font-medium text-gray-700 mb-1";
  const areaCls = `${inputCls} min-h-[96px] resize-none`;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold text-gray-900">
          {reportId ? "Edit Report" : "New Report"}
        </h1>
        <button
          onClick={handleSaveDraft}
          disabled={saving}
          className="flex items-center gap-1.5 text-sm text-gray-600 border border-gray-300 rounded-xl px-3 py-2 hover:bg-gray-50 disabled:opacity-50 transition-colors"
        >
          <Save className="w-4 h-4" />
          {saving ? "Saving..." : "Save Draft"}
        </button>
      </div>

      {/* Step indicator */}
      <div className="flex items-center gap-1 overflow-x-auto pb-1">
        {STEPS.map((s, i) => (
          <button
            key={s}
            onClick={() => setStep(i)}
            className={`flex-shrink-0 text-xs px-2.5 py-1 rounded-full font-medium transition-colors ${
              i === step ? "bg-blue-600 text-white" : i < step ? "bg-blue-100 text-blue-700" : "bg-gray-100 text-gray-500"
            }`}
          >
            {i + 1}. {s}
          </button>
        ))}
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-xl px-4 py-3">{error}</div>
      )}

      <div className="bg-white rounded-2xl border border-gray-200 p-5 space-y-4">
        {/* Step 0: Header */}
        {step === 0 && (
          <>
            <h2 className="font-semibold text-gray-800">Header Info</h2>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelCls}>Date *</label>
                <input type="date" className={inputCls} value={form.date} onChange={(e) => set("date", e.target.value)} required />
              </div>
              <div>
                <label className={labelCls}>Job No.</label>
                <input type="text" className={inputCls} value={form.jobNo} onChange={(e) => set("jobNo", e.target.value)} placeholder="Optional" />
              </div>
            </div>
          </>
        )}

        {/* Step 1: Customer */}
        {step === 1 && (
          <>
            <h2 className="font-semibold text-gray-800">Customer Information</h2>
            <div>
              <label className={labelCls}>Customer Name</label>
              <input type="text" className={inputCls} value={form.customerName} onChange={(e) => set("customerName", e.target.value)} />
            </div>
            <div>
              <label className={labelCls}>Address</label>
              <textarea className={areaCls} value={form.customerAddress} onChange={(e) => set("customerAddress", e.target.value)} rows={2} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelCls}>Contact Person</label>
                <input type="text" className={inputCls} value={form.contactPerson} onChange={(e) => set("contactPerson", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Telephone</label>
                <input type="tel" className={inputCls} value={form.telephone} onChange={(e) => set("telephone", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Fax</label>
                <input type="tel" className={inputCls} value={form.fax} onChange={(e) => set("fax", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Email</label>
                <input type="email" className={inputCls} value={form.customerEmail} onChange={(e) => set("customerEmail", e.target.value)} />
              </div>
            </div>
          </>
        )}

        {/* Step 2: Job Category + Equipment */}
        {step === 2 && (
          <>
            <h2 className="font-semibold text-gray-800">Job Category</h2>
            <div className="flex flex-wrap gap-2">
              {Object.entries(JOB_CATEGORY_LABELS).map(([key, label]) => (
                <button
                  key={key}
                  type="button"
                  onClick={() => set("jobCategory", form.jobCategory === key ? "" : key)}
                  className={`px-3 py-1.5 rounded-xl text-sm font-medium border transition-colors ${
                    form.jobCategory === key
                      ? "bg-blue-600 text-white border-blue-600"
                      : "bg-white text-gray-700 border-gray-300 hover:border-blue-400"
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>

            <h2 className="font-semibold text-gray-800 pt-2">Equipment / System</h2>
            <div>
              <label className={labelCls}>Equipment</label>
              <input type="text" className={inputCls} value={form.equipment} onChange={(e) => set("equipment", e.target.value)} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelCls}>Make</label>
                <input type="text" className={inputCls} value={form.make} onChange={(e) => set("make", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Model</label>
                <input type="text" className={inputCls} value={form.model} onChange={(e) => set("model", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Date Installed</label>
                <input type="date" className={inputCls} value={form.dateInstalled} onChange={(e) => set("dateInstalled", e.target.value)} />
              </div>
              <div>
                <label className={labelCls}>Serial No.</label>
                <input type="text" className={inputCls} value={form.serialNo} onChange={(e) => set("serialNo", e.target.value)} />
              </div>
            </div>
          </>
        )}

        {/* Step 3: Intervention */}
        {step === 3 && (
          <>
            <h2 className="font-semibold text-gray-800">Nature of Intervention / Fault Reported</h2>
            <textarea className={areaCls} value={form.natureOfIntervention} onChange={(e) => set("natureOfIntervention", e.target.value)} rows={4} placeholder="Describe the fault or reason for intervention..." />

            <h2 className="font-semibold text-gray-800">Action Taken / Work Done</h2>
            <textarea className={areaCls} value={form.actionTaken} onChange={(e) => set("actionTaken", e.target.value)} rows={4} placeholder="Describe what was done..." />

            <div className="flex items-center gap-3 pt-1">
              <span className="text-sm font-medium text-gray-700">Work Completed?</span>
              <button
                type="button"
                onClick={() => set("workCompleted", true)}
                className={`px-3 py-1.5 rounded-xl text-sm font-medium border transition-colors ${form.workCompleted ? "bg-green-600 text-white border-green-600" : "bg-white text-gray-700 border-gray-300"}`}
              >
                YES
              </button>
              <button
                type="button"
                onClick={() => set("workCompleted", false)}
                className={`px-3 py-1.5 rounded-xl text-sm font-medium border transition-colors ${!form.workCompleted ? "bg-red-600 text-white border-red-600" : "bg-white text-gray-700 border-gray-300"}`}
              >
                NO
              </button>
            </div>

            {!form.workCompleted && (
              <div>
                <label className={labelCls}>Please give details if NO</label>
                <textarea className={areaCls} value={form.workNotCompletedDetails} onChange={(e) => set("workNotCompletedDetails", e.target.value)} rows={3} />
              </div>
            )}

            <div>
              <label className={labelCls}>Equipment Under Warranty</label>
              <div className="flex gap-2">
                {["YES", "NO", "DN"].map((v) => (
                  <button
                    key={v}
                    type="button"
                    onClick={() => set("equipmentUnderWarranty", form.equipmentUnderWarranty === v ? "" : v)}
                    className={`px-3 py-1.5 rounded-xl text-sm font-medium border transition-colors ${
                      form.equipmentUnderWarranty === v
                        ? "bg-blue-600 text-white border-blue-600"
                        : "bg-white text-gray-700 border-gray-300"
                    }`}
                  >
                    {v}
                  </button>
                ))}
              </div>
            </div>
          </>
        )}

        {/* Step 4: Technicians */}
        {step === 4 && (
          <>
            <h2 className="font-semibold text-gray-800">Technicians Involved</h2>
            {([1, 2, 3] as const).map((n) => {
              const nameKey = `tech${n}Name` as keyof FormData;
              const inKey = `tech${n}TimeIn` as keyof FormData;
              const outKey = `tech${n}TimeOut` as keyof FormData;
              const duration = calcDuration(form[inKey] as string, form[outKey] as string);

              return (
                <div key={n} className="border border-gray-200 rounded-xl p-3 space-y-2">
                  <p className="text-xs font-semibold text-gray-500 uppercase">Technician {n}</p>
                  <div>
                    <label className={labelCls}>Name</label>
                    <input type="text" className={inputCls} value={form[nameKey] as string} onChange={(e) => set(nameKey, e.target.value)} />
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <div>
                      <label className={labelCls}>Time In</label>
                      <input type="time" className={inputCls} value={form[inKey] as string} onChange={(e) => set(inKey, e.target.value)} />
                    </div>
                    <div>
                      <label className={labelCls}>Time Out</label>
                      <input type="time" className={inputCls} value={form[outKey] as string} onChange={(e) => set(outKey, e.target.value)} />
                    </div>
                    <div>
                      <label className={labelCls}>Duration</label>
                      <div className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm bg-gray-50 text-gray-600">
                        {duration || "—"}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </>
        )}

        {/* Step 5: Report & Signatures */}
        {step === 5 && (
          <>
            <h2 className="font-semibold text-gray-800">Technician&apos;s Report</h2>
            <textarea className={areaCls} value={form.techniciansReport} onChange={(e) => set("techniciansReport", e.target.value)} rows={4} />

            <h2 className="font-semibold text-gray-800">Comments / Recommendations</h2>
            <textarea className={areaCls} value={form.comments} onChange={(e) => set("comments", e.target.value)} rows={3} />

            <div className="grid grid-cols-2 gap-4 pt-2">
              <div className="space-y-3">
                <p className="text-xs font-bold text-gray-500 uppercase">For the Customer</p>
                <div>
                  <label className={labelCls}>Name</label>
                  <input type="text" className={inputCls} value={form.customerSignName} onChange={(e) => set("customerSignName", e.target.value)} />
                </div>
                <div>
                  <label className={labelCls}>Job Title</label>
                  <input type="text" className={inputCls} value={form.customerSignTitle} onChange={(e) => set("customerSignTitle", e.target.value)} />
                </div>
              </div>
              <div className="space-y-3">
                <p className="text-xs font-bold text-gray-500 uppercase">For Technet</p>
                <div>
                  <label className={labelCls}>Name</label>
                  <input type="text" className={inputCls} value={form.technetSignName} onChange={(e) => set("technetSignName", e.target.value)} />
                </div>
                <div>
                  <label className={labelCls}>Job Title</label>
                  <input type="text" className={inputCls} value={form.technetSignTitle} onChange={(e) => set("technetSignTitle", e.target.value)} />
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Navigation */}
      <div className="flex items-center justify-between gap-3">
        <button
          onClick={() => setStep((s) => Math.max(0, s - 1))}
          disabled={step === 0}
          className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-30 transition-colors"
        >
          <ChevronLeft className="w-4 h-4" />
          Back
        </button>

        {step < STEPS.length - 1 ? (
          <button
            onClick={() => setStep((s) => s + 1)}
            className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 transition-colors"
          >
            Next
            <ChevronRight className="w-4 h-4" />
          </button>
        ) : (
          <button
            onClick={handleSubmit}
            disabled={submitting || saving}
            className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl bg-green-600 text-white text-sm font-medium hover:bg-green-700 disabled:opacity-50 transition-colors"
          >
            <Send className="w-4 h-4" />
            {submitting ? "Submitting..." : "Submit Report"}
          </button>
        )}
      </div>

      <p className="text-xs text-gray-400 text-center pb-2">
        ANY COMPLAINTS SHOULD BE MADE WITHIN 24 HOURS · SURVEY AND DIAGNOSIS IS BILLABLE
      </p>
    </div>
  );
}
