"use client";

import { useEffect, useState } from "react";
import { API_URL } from '@/lib/api';

interface Customer {
  id: number;
  customerCode: string;
  clinicName: string;
}

interface Machine {
  id: number;
  machineCode: string;
  manufacturer: string;
  model: string;
  customer: { id: number };
}

interface Employee {
  id: number;
  employeeCode: string;
  fullName: string;
  designation: string;
}

interface AddServiceCallModalProps {
  onClose: () => void;
  onServiceCallAdded: () => void;
}

export default function AddServiceCallModal({
  onClose,
  onServiceCallAdded,
}: AddServiceCallModalProps) {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [machines, setMachines] = useState<Machine[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [filteredMachines, setFilteredMachines] = useState<Machine[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const [form, setForm] = useState({
    customerId: "",
    machineId: "",
    serviceType: "FIELD_SERVICE",
    warrantyType: "NO_CONTRACT",
    issueTitle: "",
    issueDescription: "",
    priority: "NORMAL",
    assignedEngineerCode: "",
    inquiryReceivedDate: new Date().toISOString().slice(0, 10),
    pickupScheduledDate: "",
    pickupAddress: "",
    demoDate: "",
    demoPaid: false,
  });

  useEffect(() => {
    Promise.all([
      fetch(`${API_URL}/api/customers`).then((r) => r.json()),
      fetch(`${API_URL}/api/machines`).then((r) => r.json()),
      fetch(`${API_URL}/api/employees`).then((r) => r.json()),
    ]).then(([c, m, e]) => {
      setCustomers(c);
      setMachines(m);
      setEmployees(e);
    });
  }, []);

  function updateField(field: string, value: string | boolean) {
    setForm((prev) => {
      const updated = { ...prev, [field]: value };

      // When customer changes, filter machines and reset machine selection
      if (field === "customerId") {
        updated.machineId = "";
        const filtered = machines.filter(
          (m) => String(m.customer?.id) === value
        );
        setFilteredMachines(filtered);
      }

      return updated;
    });
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");

    if (!form.customerId || !form.machineId) {
      setError("Please fill in Customer and Machine.");
      return;
    }

    if (form.serviceType !== "DEMONSTRATION" && !form.assignedEngineerCode) {
      setError("Please assign an engineer.");
      return;
    }

    setSubmitting(true);

    try {
      const res = await fetch(`${API_URL}/api/service-calls`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customerId: Number(form.customerId),
          machineId: Number(form.machineId),
          assignedEngineerCode: form.assignedEngineerCode || null,
          serviceType: form.serviceType,
          warrantyType: form.warrantyType,
          issueTitle: form.issueTitle,
          issueDescription: form.issueDescription,
          priority: form.priority,
          scheduledDate: null,
          inquiryReceivedDate: form.inquiryReceivedDate || null,
          pickupScheduledDate: form.pickupScheduledDate || null,
          pickupAddress: form.pickupAddress || null,
          demoDate: form.demoDate || null,
          demoPaid: form.demoPaid,
        }),
      });

      if (res.ok) {
        onServiceCallAdded();
        onClose();
      } else {
        const text = await res.text();
        setError("Failed to create service call. " + text);
      }
    } catch {
      setError("Network error. Is the backend running?");
    } finally {
      setSubmitting(false);
    }
  }

  const isWorkshop = form.serviceType === "WORKSHOP_SERVICE";
  const isDemo = form.serviceType === "DEMONSTRATION";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 px-4">
      <div className="w-full max-w-3xl rounded-2xl bg-white p-8 shadow-2xl max-h-[90vh] overflow-y-auto">
        <h2 className="text-2xl font-bold text-slate-900">Add Service Call</h2>
        <p className="mb-6 mt-1 text-sm text-slate-500">
          Create a new customer service request.
        </p>

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

        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">

          {/* Service Type */}
          <div className="col-span-2">
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Service Type <span className="text-red-500">*</span>
            </label>
            <div className="grid grid-cols-3 gap-3">
              {[
                { key: "FIELD_SERVICE", label: "Field Service" },
                { key: "WORKSHOP_SERVICE", label: "Workshop Service" },
                { key: "DEMONSTRATION", label: "Demonstration" },
              ].map((t) => (
                <button
                  key={t.key}
                  type="button"
                  onClick={() => updateField("serviceType", t.key)}
                  className={`rounded-xl border-2 px-4 py-3 text-sm font-semibold transition ${
                    form.serviceType === t.key
                      ? "border-[#1296E8] bg-[#1296E8]/5 text-[#1296E8]"
                      : "border-slate-200 text-slate-500 hover:border-slate-300"
                  }`}
                >
                  {t.label}
                </button>
              ))}
            </div>
          </div>

          {/* Customer Dropdown */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Customer <span className="text-red-500">*</span>
            </label>
            <select
              value={form.customerId}
              onChange={(e) => updateField("customerId", e.target.value)}
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              required
            >
              <option value="">Select customer...</option>
              {customers.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.clinicName} ({c.customerCode})
                </option>
              ))}
            </select>
          </div>

          {/* Machine Dropdown — filters by selected customer */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Machine <span className="text-red-500">*</span>
            </label>
            <select
              value={form.machineId}
              onChange={(e) => updateField("machineId", e.target.value)}
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              required
              disabled={!form.customerId}
            >
              <option value="">
                {form.customerId
                  ? filteredMachines.length === 0
                    ? "No machines for this customer"
                    : "Select machine..."
                  : "Select customer first"}
              </option>
              {filteredMachines.map((m) => (
                <option key={m.id} value={m.id}>
                  {m.manufacturer} {m.model} ({m.machineCode})
                </option>
              ))}
            </select>
          </div>

          {/* Warranty Type — only relevant for field/workshop */}
          {!isDemo && (
            <div className="col-span-2">
              <label className="mb-1 block text-sm font-medium text-slate-700">
                Warranty Type
              </label>
              <select
                value={form.warrantyType}
                onChange={(e) => updateField("warrantyType", e.target.value)}
                className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              >
                <option value="UNDER_WARRANTY">Under Warranty</option>
                <option value="AMC">AMC</option>
                <option value="OUT_OF_WARRANTY">Out of Warranty</option>
                <option value="NO_CONTRACT">No Service Contract</option>
              </select>
            </div>
          )}

          {/* Issue Title */}
          <div className="col-span-2">
            <label className="mb-1 block text-sm font-medium text-slate-700">
              {isDemo ? "Demo Topic" : "Issue Title"} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={form.issueTitle}
              onChange={(e) => updateField("issueTitle", e.target.value)}
              placeholder={
                isDemo
                  ? "e.g. New scaler unit demonstration"
                  : "e.g. Machine not calibrating properly"
              }
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              required
            />
          </div>

          {/* Engineer Dropdown */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Assigned Engineer {!isDemo && <span className="text-red-500">*</span>}
            </label>
            <select
              value={form.assignedEngineerCode}
              onChange={(e) =>
                updateField("assignedEngineerCode", e.target.value)
              }
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              required={!isDemo}
            >
              <option value="">Select engineer...</option>
              {employees.map((emp) => (
                <option key={emp.id} value={emp.employeeCode}>
                  {emp.fullName} ({emp.employeeCode})
                </option>
              ))}
            </select>
          </div>

          {/* Priority */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Priority
            </label>
            <select
              value={form.priority}
              onChange={(e) => updateField("priority", e.target.value)}
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
            >
              <option value="LOW">LOW</option>
              <option value="NORMAL">NORMAL</option>
              <option value="HIGH">HIGH</option>
              <option value="CRITICAL">CRITICAL</option>
            </select>
          </div>

          {/* Inquiry Received Date */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Inquiry Received Date
            </label>
            <input
              type="date"
              value={form.inquiryReceivedDate}
              onChange={(e) => updateField("inquiryReceivedDate", e.target.value)}
              className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
            />
          </div>

          {/* Workshop only: pickup date + address */}
          {isWorkshop && (
            <>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">
                  Pickup Date
                </label>
                <input
                  type="date"
                  value={form.pickupScheduledDate}
                  onChange={(e) => updateField("pickupScheduledDate", e.target.value)}
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">
                  Pickup Address
                </label>
                <input
                  type="text"
                  value={form.pickupAddress}
                  onChange={(e) => updateField("pickupAddress", e.target.value)}
                  placeholder="Clinic address for pickup"
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
            </>
          )}

          {/* Demo only: demo date + paid */}
          {isDemo && (
            <>
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-700">
                  Demo Date
                </label>
                <input
                  type="date"
                  value={form.demoDate}
                  onChange={(e) => updateField("demoDate", e.target.value)}
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
              <div className="flex items-end pb-3">
                <label className="flex items-center gap-2 text-sm font-medium text-slate-700">
                  <input
                    type="checkbox"
                    checked={form.demoPaid}
                    onChange={(e) => updateField("demoPaid", e.target.checked)}
                  />
                  Paid Demonstration
                </label>
              </div>
            </>
          )}

          {/* Issue Description */}
          <div className="col-span-2">
            <label className="mb-1 block text-sm font-medium text-slate-700">
              {isDemo ? "Demo Notes" : "Issue Description"}
            </label>
            <textarea
              value={form.issueDescription}
              onChange={(e) => updateField("issueDescription", e.target.value)}
              placeholder={isDemo ? "Demo scope and notes..." : "Describe the issue in detail..."}
              className="h-24 w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
            />
          </div>

          {/* Buttons */}
          <div className="col-span-2 mt-2 flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="rounded-xl border border-slate-200 px-5 py-3 font-semibold text-slate-700 hover:bg-slate-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="rounded-xl bg-[#EE302B] px-5 py-3 font-semibold text-white disabled:opacity-60"
            >
              {submitting ? "Saving..." : "Save Service Call"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
