"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import DashboardLayout from "@/components/layout/DashboardLayout";
import DocumentsTab from "@/components/documents/DocumentsTab";
import ActivityTimeline from "@/components/activity/ActivityTimeline";
import { API_URL } from '@/lib/api';

interface TrainingSession {
  id: number;
  trainingDate: string;
  attendeesCount: number;
  topicsCovered: string;
  notes: string;
  acknowledgedByCustomer: boolean;
  trainedBy: { fullName: string };
}

interface Customer {
  customerCode: string;
  clinicName: string;
  doctorName: string;
  phone: string;
  emirate: string;
}

interface Machine {
  machineCode: string;
  manufacturer: string;
  model: string;
  serialNumber: string;
  warrantyExpiryDate?: string;
  amcExpiryDate?: string;
}

interface RepairApproval {
  id: number;
  estimatedCost: number;
  reason: string;
  status: string;
  decisionNotes: string;
  requestedAt: string;
  decidedAt: string;
  requestedBy: { fullName: string };
  decidedBy: { fullName: string };
}

interface Quotation {
  id: number;
  quotationCode: string;
  itemsSummary: string;
  totalAmount: number;
  advancePercent: number;
  advanceAmount: number;
  status: string;
  lpoReference: string;
  lpoReceivedDate: string;
  sentDate: string;
  notes: string;
  createdAt: string;
}

interface Satisfaction {
  id: number;
  rating: number;
  feedback: string;
  wouldRecommend: boolean;
  recordedAt: string;
}

interface Employee {
  employeeCode: string;
  fullName: string;
  phone: string;
}

interface ServiceCall {
  id: number;
  serviceCallCode: string;
  serviceType: string;
  warrantyType: string;
  customer: Customer;
  machine: Machine;
  issueTitle: string;
  issueDescription: string;
  priority: string;
  status: string;
  workflowStatus: string;
  assignedEngineer: Employee;
  scheduledDate: string;
  serviceReport: string;
  createdAt: string;
  pickupScheduledDate?: string;
  pickupAddress?: string;
  observationNotes?: string;
  deliveryDate?: string;
  inquiryReceivedDate?: string;
  estimatedCompletionDate?: string;
}

interface WorkSession {
  id: number;
  workDate: string;
  hoursSpent: number;
  notes: string;
  engineer: { fullName: string; employeeCode: string };
}

const FIELD_SERVICE_STEPS = [
  { key: "INQUIRY_RECEIVED", label: "Inquiry Received" },
  { key: "VERIFICATION_DONE", label: "Verification Done" },
  { key: "REGISTERED", label: "Registered" },
  { key: "ENGINEER_ASSIGNED", label: "Engineer Assigned" },
  { key: "INSPECTION_SCHEDULED", label: "Inspection Scheduled" },
  { key: "QUOTATION_SENT", label: "Quotation Sent" },
  { key: "LPO_RECEIVED", label: "LPO Received" },
  { key: "ADVANCE_RECEIVED", label: "Advance Received" },
  { key: "PARTS_ORDERED", label: "Parts Ordered" },
  { key: "REPAIR_STARTED", label: "Repair Started" },
  { key: "REPAIR_COMPLETED", label: "Repair Completed" },
  { key: "INVOICE_GENERATED", label: "Invoice Generated" },
  { key: "PAYMENT_RECEIVED", label: "Payment Received" },
  { key: "CLOSED", label: "Closed" },
];

const WORKSHOP_SERVICE_STEPS = [
  { key: "INQUIRY_RECEIVED", label: "Inquiry Received" },
  { key: "VERIFICATION_DONE", label: "Verification Done" },
  { key: "PICKUP_SCHEDULED", label: "Pickup Scheduled" },
  { key: "ARRIVED_AT_WORKSHOP", label: "Arrived at Workshop" },
  { key: "REGISTERED", label: "Registered" },
  { key: "OBSERVATION_DONE", label: "Observation Done" },
  { key: "QUOTATION_SENT", label: "Quotation Sent" },
  { key: "LPO_RECEIVED", label: "LPO Received" },
  { key: "ADVANCE_RECEIVED", label: "Advance Received" },
  { key: "PARTS_ORDERED", label: "Parts Ordered" },
  { key: "REPAIR_STARTED", label: "Repair Started" },
  { key: "REPAIR_COMPLETED", label: "Repair Completed" },
  { key: "INVOICE_GENERATED", label: "Invoice Generated" },
  { key: "PAYMENT_RECEIVED", label: "Payment Received" },
  { key: "DELIVERED", label: "Delivered" },
  { key: "CLOSED", label: "Closed" },
];

const DEMO_STEPS = [
  { key: "INQUIRY_RECEIVED", label: "Demo Requested" },
  { key: "ENGINEER_ASSIGNED", label: "Engineer Assigned" },
  { key: "QUOTATION_SENT", label: "Quotation Sent" },
  { key: "INVOICE_GENERATED", label: "Invoice / Service Order" },
  { key: "REPAIR_COMPLETED", label: "Demo Completed" },
  { key: "CLOSED", label: "Closed" },
];

function getWorkflowSteps(serviceType?: string) {
  if (serviceType === "WORKSHOP_SERVICE") return WORKSHOP_SERVICE_STEPS;
  if (serviceType === "DEMONSTRATION") return DEMO_STEPS;
  return FIELD_SERVICE_STEPS;
}

export default function ServiceCallProfilePage() {
  const params = useParams();
  const id = params.id?.toString();

  const [serviceCall, setServiceCall] = useState<ServiceCall | null>(null);
  const [attachmentCount, setAttachmentCount] = useState(0);
  const [activityCount, setActivityCount] = useState(0);
  const [updatingWorkflow, setUpdatingWorkflow] = useState(false);
  const [trainingSessions, setTrainingSessions] = useState<TrainingSession[]>([]);
  const [showTrainingForm, setShowTrainingForm] = useState(false);
  const [trainingForm, setTrainingForm] = useState({
    attendeesCount: "",
    topicsCovered: "",
    notes: "",
    acknowledgedByCustomer: false,
  });
  const [savingTraining, setSavingTraining] = useState(false);
  const [approvals, setApprovals] = useState<RepairApproval[]>([]);
  const [showApprovalForm, setShowApprovalForm] = useState(false);
  const [approvalForm, setApprovalForm] = useState({ estimatedCost: "", reason: "" });
  const [savingApproval, setSavingApproval] = useState(false);
  const [quotations, setQuotations] = useState<Quotation[]>([]);
  const [savingQuote, setSavingQuote] = useState(false);
  const [lpoForm, setLpoForm] = useState<{ [id: number]: string }>({});
  const [satisfaction, setSatisfaction] = useState<Satisfaction | null>(null);
  const [satForm, setSatForm] = useState({ rating: "5", feedback: "", wouldRecommend: true });
  const [savingSat, setSavingSat] = useState(false);
  const [workSessions, setWorkSessions] = useState<WorkSession[]>([]);
  const [showSessionForm, setShowSessionForm] = useState(false);
  const [sessionForm, setSessionForm] = useState({
    engineerCode: "",
    workDate: "",
    hoursSpent: "",
    notes: "",
  });
  const [savingSession, setSavingSession] = useState(false);
  const [editingDates, setEditingDates] = useState(false);
  const [dateForm, setDateForm] = useState({
    inquiryReceivedDate: "",
    scheduledDate: "",
    estimatedCompletionDate: "",
    deliveryDate: "",
    pickupScheduledDate: "",
  });
  const [savingDates, setSavingDates] = useState(false);
  const [employees, setEmployees] = useState<{ id: number; employeeCode: string; fullName: string }[]>([]);
  const [expandedQuoteDocs, setExpandedQuoteDocs] = useState<{ [id: number]: boolean }>({});

  function loadServiceCall() {
    if (!id) return;
    fetch(`${API_URL}/api/service-calls/${id}`)
      .then((res) => res.json())
      .then((data) => setServiceCall(data))
      .catch(console.error);
  }

  function loadTraining() {
    if (!id) return;
    fetch(`${API_URL}/api/training/service-call/${id}`)
      .then((res) => res.json())
      .then((data) => setTrainingSessions(data))
      .catch(console.error);
  }

  function loadApprovals() {
    if (!id) return;
    fetch(`${API_URL}/api/approvals/service-call/${id}`)
      .then((res) => res.json())
      .then((data) => setApprovals(data))
      .catch(console.error);
  }

  function loadQuotations() {
    if (!id) return;
    fetch(`${API_URL}/api/quotations/service-call/${id}`)
      .then((res) => res.json())
      .then((data) => setQuotations(data))
      .catch(console.error);
  }

  function loadSatisfaction() {
    if (!id) return;
    fetch(`${API_URL}/api/satisfaction/service-call/${id}`)
      .then((res) => (res.ok ? res.text() : Promise.resolve("")))
      .then((text) => setSatisfaction(text ? JSON.parse(text) : null))
      .catch(console.error);
  }

  function loadWorkSessions() {
    if (!id) return;
    fetch(`${API_URL}/api/work-sessions/service-call/${id}`)
      .then((res) => res.json())
      .then((data) => setWorkSessions(data))
      .catch(console.error);
  }

  useEffect(() => {
    loadServiceCall();
    loadTraining();
    loadApprovals();
    loadQuotations();
    loadSatisfaction();
    loadWorkSessions();
    fetch(`${API_URL}/api/employees`)
      .then((res) => res.json())
      .then((data) => setEmployees(data))
      .catch(console.error);
  }, [id]);

  useEffect(() => {
    if (serviceCall) {
      setDateForm({
        inquiryReceivedDate: serviceCall.inquiryReceivedDate?.slice(0, 10) || "",
        scheduledDate: serviceCall.scheduledDate?.slice(0, 10) || "",
        estimatedCompletionDate: serviceCall.estimatedCompletionDate?.slice(0, 10) || "",
        deliveryDate: serviceCall.deliveryDate?.slice(0, 10) || "",
        pickupScheduledDate: serviceCall.pickupScheduledDate?.slice(0, 10) || "",
      });
    }
  }, [serviceCall]);

  async function submitApproval() {
    if (!id) return;
    setSavingApproval(true);
    try {
      await fetch(`${API_URL}/api/approvals`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serviceCallId: Number(id),
          estimatedCost: approvalForm.estimatedCost ? Number(approvalForm.estimatedCost) : null,
          reason: approvalForm.reason,
        }),
      });
      setApprovalForm({ estimatedCost: "", reason: "" });
      setShowApprovalForm(false);
      loadApprovals();
    } finally {
      setSavingApproval(false);
    }
  }

  async function decideApproval(approvalId: number, status: string) {
    await fetch(`${API_URL}/api/approvals/${approvalId}/decision`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    loadApprovals();
  }

  async function createBareQuotation() {
    if (!id) return;
    setSavingQuote(true);
    try {
      const res = await fetch(`${API_URL}/api/quotations`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serviceCallId: Number(id),
        }),
      });
      const created = await res.json();
      await loadQuotations();
      if (created?.id) {
        setExpandedQuoteDocs((prev) => ({ ...prev, [created.id]: true }));
      }
    } finally {
      setSavingQuote(false);
    }
  }

  async function sendQuotation(quoteId: number) {
    await fetch(`${API_URL}/api/quotations/${quoteId}/send`, {
      method: "PATCH",
    });
    loadQuotations();
  }

  async function recordLpo(quoteId: number) {
    const lpoReference = lpoForm[quoteId];
    if (!lpoReference) return;
    await fetch(`${API_URL}/api/quotations/${quoteId}/lpo`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ lpoReference }),
    });
    setLpoForm({ ...lpoForm, [quoteId]: "" });
    loadQuotations();
  }

  async function rejectQuotation(quoteId: number) {
    await fetch(`${API_URL}/api/quotations/${quoteId}/reject`, {
      method: "PATCH",
    });
    loadQuotations();
  }

  async function submitSatisfaction() {
    if (!id) return;
    setSavingSat(true);
    try {
      await fetch(`${API_URL}/api/satisfaction/service-call/${id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          rating: Number(satForm.rating),
          feedback: satForm.feedback,
          wouldRecommend: satForm.wouldRecommend,
        }),
      });
      loadSatisfaction();
    } finally {
      setSavingSat(false);
    }
  }

  async function submitWorkSession() {
    if (!id) return;
    if (!sessionForm.engineerCode || !sessionForm.workDate || !sessionForm.hoursSpent) return;
    setSavingSession(true);
    try {
      await fetch(`${API_URL}/api/work-sessions`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serviceCallId: Number(id),
          engineerCode: sessionForm.engineerCode,
          workDate: sessionForm.workDate,
          hoursSpent: Number(sessionForm.hoursSpent),
          notes: sessionForm.notes,
        }),
      });
      setSessionForm({ engineerCode: "", workDate: "", hoursSpent: "", notes: "" });
      setShowSessionForm(false);
      loadWorkSessions();
    } finally {
      setSavingSession(false);
    }
  }

  async function deleteWorkSession(sessionId: number) {
    await fetch(`${API_URL}/api/work-sessions/${sessionId}`, {
      method: "DELETE",
    });
    loadWorkSessions();
  }

  async function saveDates() {
    if (!id) return;
    setSavingDates(true);
    try {
      await fetch(`${API_URL}/api/service-calls/${id}/dates`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          inquiryReceivedDate: dateForm.inquiryReceivedDate || null,
          scheduledDate: dateForm.scheduledDate || null,
          estimatedCompletionDate: dateForm.estimatedCompletionDate || null,
          deliveryDate: dateForm.deliveryDate || null,
          pickupScheduledDate: dateForm.pickupScheduledDate || null,
        }),
      });
      setEditingDates(false);
      loadServiceCall();
    } finally {
      setSavingDates(false);
    }
  }

  const totalHoursLogged = workSessions.reduce(
    (sum, s) => sum + (s.hoursSpent || 0),
    0
  );

  async function submitTraining() {
    if (!id) return;
    setSavingTraining(true);
    try {
      await fetch(`${API_URL}/api/training`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serviceCallId: Number(id),
          attendeesCount: trainingForm.attendeesCount
            ? Number(trainingForm.attendeesCount)
            : null,
          topicsCovered: trainingForm.topicsCovered,
          notes: trainingForm.notes,
          acknowledgedByCustomer: trainingForm.acknowledgedByCustomer,
        }),
      });
      setTrainingForm({
        attendeesCount: "",
        topicsCovered: "",
        notes: "",
        acknowledgedByCustomer: false,
      });
      setShowTrainingForm(false);
      loadTraining();
    } finally {
      setSavingTraining(false);
    }
  }

  async function handleWorkflowChange(workflowStatus: string) {
    if (!id || updatingWorkflow) return;
    setUpdatingWorkflow(true);
    try {
      const res = await fetch(
        `${API_URL}/api/service-calls/${id}/workflow`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ workflowStatus }),
        }
      );
      if (res.ok) loadServiceCall();
    } finally {
      setUpdatingWorkflow(false);
    }
  }

  async function handleStatusChange(status: string) {
    if (!id) return;
    await fetch(`${API_URL}/api/service-calls/${id}/status`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    loadServiceCall();
  }

  function formatDate(date?: string) {
    if (!date) return "—";
    return new Date(date).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });
  }

  if (!serviceCall) {
    return (
      <DashboardLayout>
        <p className="text-slate-500">Loading service call...</p>
      </DashboardLayout>
    );
  }

  const workflowSteps = getWorkflowSteps(serviceCall.serviceType);

  const currentStepIndex = workflowSteps.findIndex(
    (s) => s.key === serviceCall.workflowStatus
  );

  const today = new Date();
  const isOutOfWarranty =
    (!serviceCall.machine?.warrantyExpiryDate ||
      new Date(serviceCall.machine.warrantyExpiryDate) < today) &&
    (!serviceCall.machine?.amcExpiryDate ||
      new Date(serviceCall.machine.amcExpiryDate) < today);

  const latestApproval = approvals[0];

  return (
    <DashboardLayout>
      {/* Breadcrumb */}
      <div className="mb-6 text-sm text-slate-500">
        <span className="hover:text-slate-700 cursor-pointer" onClick={() => window.history.back()}>
          Service Calls
        </span>{" "}
        /{" "}
        <span className="font-semibold text-[#1296E8]">
          {serviceCall.serviceCallCode}
        </span>
      </div>

      {/* Header Card */}
      <div className="mb-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-sm font-semibold text-[#1296E8]">
              {serviceCall.serviceCallCode}
            </p>
            <h1 className="mt-1 text-3xl font-bold text-slate-900">
              {serviceCall.issueTitle}
            </h1>
            <p className="mt-2 text-slate-500">
              {serviceCall.customer?.clinicName || "—"} •{" "}
              {serviceCall.machine
                ? `${serviceCall.machine.manufacturer} ${serviceCall.machine.model}`
                : "—"}
            </p>
            <p className="mt-1 text-xs text-slate-400">
              Created {formatDate(serviceCall.createdAt)}
            </p>
          </div>

          <div className="flex flex-wrap gap-3">
            <Badge value={serviceCall.serviceType} />
            <Badge value={serviceCall.priority} />
            <Badge value={serviceCall.status} />
          </div>
        </div>

        {/* Action Buttons */}
        <div className="mt-6 flex flex-wrap gap-3">
          {serviceCall.status === "OPEN" && (
            <button
              onClick={() => handleStatusChange("IN_PROGRESS")}
              className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white hover:opacity-90"
            >
              Start Work
            </button>
          )}
          {serviceCall.status === "IN_PROGRESS" && (
            <button
              onClick={() => handleStatusChange("COMPLETED")}
              className="rounded-xl bg-green-600 px-5 py-2.5 text-sm font-semibold text-white hover:opacity-90"
            >
              Mark Complete
            </button>
          )}
          {serviceCall.status !== "CLOSED" && (
            <button
              onClick={() => handleStatusChange("CLOSED")}
              className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50"
            >
              Close Call
            </button>
          )}
        </div>
      </div>

      {/* Workflow Progress */}
      <div className="mb-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <h3 className="mb-6 text-lg font-bold text-slate-900">
          Workflow Progress
        </h3>
        <div className="flex items-start gap-0 overflow-x-auto pb-2">
          {workflowSteps.map((step, index) => {
            const isDone = index < currentStepIndex;
            const isCurrent = index === currentStepIndex;
            const isNext = index === currentStepIndex + 1;

            return (
              <div key={step.key} className="flex items-center">
                <div className="flex flex-col items-center min-w-[90px]">
                  <button
                    onClick={() =>
                      isNext && handleWorkflowChange(step.key)
                    }
                    disabled={!isNext || updatingWorkflow}
                    className={`h-9 w-9 rounded-full border-2 text-xs font-bold transition
                      ${isDone
                        ? "border-[#1296E8] bg-[#1296E8] text-white"
                        : isCurrent
                        ? "border-[#EE302B] bg-[#EE302B] text-white"
                        : isNext
                        ? "border-slate-300 bg-white text-slate-400 hover:border-[#1296E8] hover:text-[#1296E8] cursor-pointer"
                        : "border-slate-200 bg-slate-50 text-slate-300 cursor-default"
                      }`}
                  >
                    {isDone ? "✓" : index + 1}
                  </button>
                  <span
                    className={`mt-2 text-center text-[10px] font-medium leading-tight max-w-[80px]
                      ${isCurrent ? "text-[#EE302B]" : isDone ? "text-[#1296E8]" : "text-slate-400"}`}
                  >
                    {step.label}
                  </span>
                </div>

                {index < workflowSteps.length - 1 && (
                  <div
                    className={`h-0.5 w-8 shrink-0 -mt-5 ${
                      isDone ? "bg-[#1296E8]" : "bg-slate-200"
                    }`}
                  />
                )}
              </div>
            );
          })}
        </div>
        <p className="mt-4 text-xs text-slate-400">
          Click the next step to advance the workflow.
        </p>
      </div>

      {/* Info Cards */}
      <div className="grid gap-6 lg:grid-cols-3">
        <Card title="Customer">
          <Info label="Clinic" value={serviceCall.customer?.clinicName} />
          <Info label="Code" value={serviceCall.customer?.customerCode} />
          <Info label="Doctor" value={serviceCall.customer?.doctorName} />
          <Info label="Phone" value={serviceCall.customer?.phone} />
          <Info label="Emirate" value={serviceCall.customer?.emirate} />
        </Card>

        <Card title="Machine">
          <Info label="Code" value={serviceCall.machine?.machineCode} />
          <Info
            label="Machine"
            value={
              serviceCall.machine
                ? `${serviceCall.machine.manufacturer} ${serviceCall.machine.model}`
                : "—"
            }
          />
          <Info label="Serial Number" value={serviceCall.machine?.serialNumber} />
        </Card>

        <Card title="Assignment">
          <Info
            label="Assigned Engineer"
            value={serviceCall.assignedEngineer?.fullName}
          />
          <Info
            label="Employee Code"
            value={serviceCall.assignedEngineer?.employeeCode}
          />
          <Info label="Scheduled Date" value={formatDate(serviceCall.scheduledDate)} />
        </Card>

        {serviceCall.serviceType === "WORKSHOP_SERVICE" && (
          <Card title="Pickup & Delivery">
            <Info label="Pickup Date" value={formatDate(serviceCall.pickupScheduledDate)} />
            <Info label="Pickup Address" value={serviceCall.pickupAddress} />
            <Info label="Delivery Date" value={formatDate(serviceCall.deliveryDate)} />
          </Card>
        )}
      </div>

      {/* Flexible Dates — all editable, change any time as circumstances shift */}
      <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h3 className="text-lg font-bold text-slate-900">Schedule Dates</h3>
            <p className="mt-1 text-sm text-slate-500">
              Every date here can be changed at any time as the job progresses.
            </p>
          </div>
          <button
            onClick={() => setEditingDates((prev) => !prev)}
            className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
          >
            {editingDates ? "Cancel" : "Edit Dates"}
          </button>
        </div>

        {!editingDates ? (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <Info label="Inquiry Received" value={formatDate(serviceCall.inquiryReceivedDate)} />
            <Info label="Site Visit / Scheduled" value={formatDate(serviceCall.scheduledDate)} />
            <Info
              label="Est. Completion"
              value={formatDate(serviceCall.estimatedCompletionDate)}
            />
            {serviceCall.serviceType === "WORKSHOP_SERVICE" ? (
              <Info label="Delivery Date" value={formatDate(serviceCall.deliveryDate)} />
            ) : null}
          </div>
        ) : (
          <div className="space-y-4 rounded-xl border border-slate-200 bg-slate-50 p-5">
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">
                  Inquiry Received
                </label>
                <input
                  type="date"
                  value={dateForm.inquiryReceivedDate}
                  onChange={(e) =>
                    setDateForm({ ...dateForm, inquiryReceivedDate: e.target.value })
                  }
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
              <div>
                <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">
                  Site Visit / Scheduled Date
                </label>
                <input
                  type="date"
                  value={dateForm.scheduledDate}
                  onChange={(e) => setDateForm({ ...dateForm, scheduledDate: e.target.value })}
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
              <div>
                <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">
                  Estimated Completion (rough estimate)
                </label>
                <input
                  type="date"
                  value={dateForm.estimatedCompletionDate}
                  onChange={(e) =>
                    setDateForm({ ...dateForm, estimatedCompletionDate: e.target.value })
                  }
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                />
              </div>
              {serviceCall.serviceType === "WORKSHOP_SERVICE" && (
                <>
                  <div>
                    <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">
                      Pickup Date
                    </label>
                    <input
                      type="date"
                      value={dateForm.pickupScheduledDate}
                      onChange={(e) =>
                        setDateForm({ ...dateForm, pickupScheduledDate: e.target.value })
                      }
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">
                      Delivery Date
                    </label>
                    <input
                      type="date"
                      value={dateForm.deliveryDate}
                      onChange={(e) =>
                        setDateForm({ ...dateForm, deliveryDate: e.target.value })
                      }
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                    />
                  </div>
                </>
              )}
            </div>
            <button
              disabled={savingDates}
              onClick={saveDates}
              className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
            >
              {savingDates ? "Saving..." : "Save Dates"}
            </button>
          </div>
        )}
      </div>

      {/* Work Sessions — multiple engineers can log time across multiple days */}
      <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <h3 className="text-xl font-bold text-slate-900">Work Sessions</h3>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-600">
              {workSessions.length}
            </span>
            {totalHoursLogged > 0 && (
              <span className="rounded-full bg-[#1296E8]/10 px-3 py-1 text-sm font-semibold text-[#1296E8]">
                {totalHoursLogged} hrs total
              </span>
            )}
          </div>
          <button
            onClick={() => setShowSessionForm((prev) => !prev)}
            className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
          >
            {showSessionForm ? "Cancel" : "+ Log Work Session"}
          </button>
        </div>

        <p className="mb-6 text-sm text-slate-500">
          Track every engineer who worked on this job and how long they spent —
          useful when the repair spans multiple visits or hands off between engineers.
        </p>

        {showSessionForm && (
          <div className="mb-6 space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-5">
            <div className="grid grid-cols-3 gap-3">
              <select
                value={sessionForm.engineerCode}
                onChange={(e) => setSessionForm({ ...sessionForm, engineerCode: e.target.value })}
                className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              >
                <option value="">Select engineer...</option>
                {employees.map((emp) => (
                  <option key={emp.id} value={emp.employeeCode}>
                    {emp.fullName} ({emp.employeeCode})
                  </option>
                ))}
              </select>
              <input
                type="date"
                value={sessionForm.workDate}
                onChange={(e) => setSessionForm({ ...sessionForm, workDate: e.target.value })}
                className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
              <input
                type="number"
                step="0.5"
                placeholder="Hours spent"
                value={sessionForm.hoursSpent}
                onChange={(e) => setSessionForm({ ...sessionForm, hoursSpent: e.target.value })}
                className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
            </div>
            <textarea
              placeholder="What did they work on? (optional)"
              value={sessionForm.notes}
              onChange={(e) => setSessionForm({ ...sessionForm, notes: e.target.value })}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              rows={2}
            />
            <button
              disabled={savingSession}
              onClick={submitWorkSession}
              className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
            >
              {savingSession ? "Saving..." : "Save Session"}
            </button>
          </div>
        )}

        {workSessions.length === 0 ? (
          <p className="text-slate-500">No work sessions logged yet.</p>
        ) : (
          <div className="space-y-3">
            {workSessions.map((session) => (
              <div
                key={session.id}
                className="flex items-start justify-between rounded-xl border border-slate-200 p-4"
              >
                <div>
                  <span className="text-sm font-semibold text-slate-900">
                    {session.engineer?.fullName || "—"} • {formatDate(session.workDate)} •{" "}
                    {session.hoursSpent} hrs
                  </span>
                  {session.notes && (
                    <p className="mt-1 text-sm text-slate-600">{session.notes}</p>
                  )}
                </div>
                <button
                  onClick={() => deleteWorkSession(session.id)}
                  className="text-xs font-semibold text-slate-400 hover:text-[#EE302B]"
                >
                  Remove
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Observation Notes (workshop only) */}
      {serviceCall.serviceType === "WORKSHOP_SERVICE" && (
        <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <h3 className="mb-3 text-lg font-bold">Observation / Inspection Notes</h3>
          <p className="text-slate-600">
            {serviceCall.observationNotes || "No observation recorded yet."}
          </p>
        </div>
      )}

      {/* Description + Report */}
      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <h3 className="mb-3 text-lg font-bold">Issue Description</h3>
          <p className="text-slate-600">
            {serviceCall.issueDescription || "No issue description added."}
          </p>
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <h3 className="mb-3 text-lg font-bold">Service Report</h3>
          <p className="mb-5 text-slate-600">
            {serviceCall.serviceReport || "No service report added yet."}
          </p>
          <DocumentsTab
            entityType="SERVICE_REPORT"
            entityId={serviceCall.id}
          />
        </div>
      </div>

      {/* Quotations & LPO */}
      <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <h3 className="text-xl font-bold text-slate-900">Quotations & LPO</h3>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-600">
              {quotations.length}
            </span>
          </div>
          <button
            disabled={savingQuote}
            onClick={createBareQuotation}
            className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50"
          >
            {savingQuote ? "Creating..." : "+ New Quotation"}
          </button>
        </div>

        <p className="mb-6 text-sm text-slate-500">
          Drop the quotation document (and later the LPO/PO document) straight
          onto each quotation below — no need to retype the numbers.
        </p>

        {quotations.length === 0 ? (
          <p className="text-slate-500">No quotations created yet.</p>
        ) : (
          <div className="space-y-3">
            {quotations.map((q) => (
              <div key={q.id} className="rounded-xl border border-slate-200 p-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-semibold text-slate-900">
                    {q.quotationCode}
                    {q.totalAmount != null ? ` • AED ${q.totalAmount}` : ""}
                  </span>
                  <span
                    className={`rounded-full px-3 py-1 text-xs font-semibold ${
                      q.status === "APPROVED" || q.status === "LPO_RECEIVED"
                        ? "bg-green-100 text-green-700"
                        : q.status === "REJECTED"
                        ? "bg-red-100 text-red-700"
                        : q.status === "SENT"
                        ? "bg-blue-100 text-blue-700"
                        : "bg-slate-100 text-slate-600"
                    }`}
                  >
                    {q.status}
                  </span>
                </div>
                {q.itemsSummary && (
                  <p className="mt-2 text-sm text-slate-600">{q.itemsSummary}</p>
                )}
                {q.advanceAmount != null && (
                  <p className="mt-1 text-xs text-slate-400">
                    Advance: AED {q.advanceAmount} ({q.advancePercent}%)
                  </p>
                )}
                {q.lpoReference && (
                  <p className="mt-1 text-xs text-slate-400">
                    LPO Ref: {q.lpoReference} ({formatDate(q.lpoReceivedDate)})
                  </p>
                )}

                <div className="mt-3 flex flex-wrap gap-2">
                  {q.status === "DRAFT" && (
                    <button
                      onClick={() => sendQuotation(q.id)}
                      className="rounded-lg bg-[#1296E8] px-4 py-2 text-xs font-semibold text-white"
                    >
                      Mark Sent
                    </button>
                  )}
                  {(q.status === "SENT" || q.status === "DRAFT") && !q.lpoReference && (
                    <>
                      <input
                        type="text"
                        placeholder="LPO / PO reference"
                        value={lpoForm[q.id] || ""}
                        onChange={(e) => setLpoForm({ ...lpoForm, [q.id]: e.target.value })}
                        className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs outline-none focus:ring-2 focus:ring-[#1296E8]"
                      />
                      <button
                        onClick={() => recordLpo(q.id)}
                        className="rounded-lg bg-green-600 px-4 py-2 text-xs font-semibold text-white"
                      >
                        Record LPO
                      </button>
                      <button
                        onClick={() => rejectQuotation(q.id)}
                        className="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                      >
                        Reject
                      </button>
                    </>
                  )}
                  <button
                    onClick={() =>
                      setExpandedQuoteDocs((prev) => ({ ...prev, [q.id]: !prev[q.id] }))
                    }
                    className="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                  >
                    {expandedQuoteDocs[q.id] ? "Hide Photos" : "Quotation / LPO Photos"}
                  </button>
                </div>

                {expandedQuoteDocs[q.id] && (
                  <div className="mt-4 rounded-lg border border-slate-200 bg-slate-50 p-4">
                    <DocumentsTab entityType="QUOTATION" entityId={q.id} />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Out-of-Warranty Approval */}
      {isOutOfWarranty && (
        <div className="mt-8 rounded-2xl border border-[#EE302B]/30 bg-[#EE302B]/5 p-8 shadow-sm">
          <div className="mb-6 flex items-center justify-between">
            <div>
              <h3 className="text-xl font-bold text-slate-900">
                Out-of-Warranty Repair Approval
              </h3>
              <p className="mt-1 text-sm text-slate-500">
                This machine&apos;s warranty and AMC have expired. Repair requires approval
                before proceeding.
              </p>
            </div>
            {(!latestApproval || latestApproval.status === "REJECTED") && (
              <button
                onClick={() => setShowApprovalForm((prev) => !prev)}
                className="rounded-xl bg-[#EE302B] px-4 py-2 text-sm font-semibold text-white"
              >
                {showApprovalForm ? "Cancel" : "Request Approval"}
              </button>
            )}
          </div>

          {showApprovalForm && (
            <div className="mb-6 space-y-3 rounded-xl border border-slate-200 bg-white p-5">
              <input
                type="number"
                placeholder="Estimated cost (AED)"
                value={approvalForm.estimatedCost}
                onChange={(e) =>
                  setApprovalForm({ ...approvalForm, estimatedCost: e.target.value })
                }
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
              <textarea
                placeholder="Reason for repair / justification"
                value={approvalForm.reason}
                onChange={(e) => setApprovalForm({ ...approvalForm, reason: e.target.value })}
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                rows={2}
              />
              <button
                disabled={savingApproval}
                onClick={submitApproval}
                className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
              >
                Submit Request
              </button>
            </div>
          )}

          {approvals.length === 0 ? (
            <p className="text-slate-500">No approval requests yet.</p>
          ) : (
            <div className="space-y-3">
              {approvals.map((approval) => (
                <div
                  key={approval.id}
                  className="rounded-xl border border-slate-200 bg-white p-4"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-semibold text-slate-900">
                      {formatDate(approval.requestedAt)} • Requested by{" "}
                      {approval.requestedBy?.fullName || "—"}
                    </span>
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-semibold ${
                        approval.status === "APPROVED"
                          ? "bg-green-100 text-green-700"
                          : approval.status === "REJECTED"
                          ? "bg-red-100 text-red-700"
                          : "bg-yellow-100 text-yellow-700"
                      }`}
                    >
                      {approval.status}
                    </span>
                  </div>
                  {approval.estimatedCost != null && (
                    <p className="mt-1 text-sm text-slate-500">
                      Estimated cost: AED {approval.estimatedCost}
                    </p>
                  )}
                  {approval.reason && (
                    <p className="mt-2 text-sm text-slate-600">{approval.reason}</p>
                  )}
                  {approval.status === "PENDING" && (
                    <div className="mt-3 flex gap-2">
                      <button
                        onClick={() => decideApproval(approval.id, "APPROVED")}
                        className="rounded-lg bg-green-600 px-4 py-2 text-xs font-semibold text-white"
                      >
                        Approve
                      </button>
                      <button
                        onClick={() => decideApproval(approval.id, "REJECTED")}
                        className="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                      >
                        Reject
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Customer Training */}
      <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <h3 className="text-xl font-bold text-slate-900">Customer Training</h3>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-600">
              {trainingSessions.length}
            </span>
          </div>
          <button
            onClick={() => setShowTrainingForm((prev) => !prev)}
            className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
          >
            {showTrainingForm ? "Cancel" : "Log Training Session"}
          </button>
        </div>

        {showTrainingForm && (
          <div className="mb-6 space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-5">
            <div className="grid grid-cols-2 gap-3">
              <input
                type="number"
                placeholder="Attendees count"
                value={trainingForm.attendeesCount}
                onChange={(e) =>
                  setTrainingForm({ ...trainingForm, attendeesCount: e.target.value })
                }
                className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
              <label className="flex items-center gap-2 text-sm text-slate-700">
                <input
                  type="checkbox"
                  checked={trainingForm.acknowledgedByCustomer}
                  onChange={(e) =>
                    setTrainingForm({
                      ...trainingForm,
                      acknowledgedByCustomer: e.target.checked,
                    })
                  }
                />
                Acknowledged by customer
              </label>
            </div>
            <textarea
              placeholder="Topics covered"
              value={trainingForm.topicsCovered}
              onChange={(e) =>
                setTrainingForm({ ...trainingForm, topicsCovered: e.target.value })
              }
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              rows={2}
            />
            <textarea
              placeholder="Notes"
              value={trainingForm.notes}
              onChange={(e) => setTrainingForm({ ...trainingForm, notes: e.target.value })}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              rows={2}
            />
            <button
              disabled={savingTraining}
              onClick={submitTraining}
              className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
            >
              Save Training Session
            </button>
          </div>
        )}

        {trainingSessions.length === 0 ? (
          <p className="text-slate-500">No training sessions logged yet.</p>
        ) : (
          <div className="space-y-4">
            {trainingSessions.map((session) => (
              <div
                key={session.id}
                className="rounded-xl border border-slate-200 p-4"
              >
                <div className="flex items-center justify-between">
                  <span className="text-sm font-semibold text-slate-900">
                    {formatDate(session.trainingDate)} • {session.trainedBy?.fullName || "—"}
                  </span>
                  {session.acknowledgedByCustomer ? (
                    <span className="rounded-full bg-green-100 px-3 py-1 text-xs font-semibold text-green-700">
                      Acknowledged
                    </span>
                  ) : (
                    <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">
                      Pending Ack.
                    </span>
                  )}
                </div>
                {session.attendeesCount != null && (
                  <p className="mt-1 text-sm text-slate-500">
                    Attendees: {session.attendeesCount}
                  </p>
                )}
                {session.topicsCovered && (
                  <p className="mt-2 text-sm text-slate-600">{session.topicsCovered}</p>
                )}
                {session.notes && (
                  <p className="mt-1 text-xs text-slate-400">{session.notes}</p>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Attachments + Activity */}
      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <div className="mb-6 flex items-center gap-3">
            <h3 className="text-xl font-bold text-slate-900">Attachments</h3>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-600">
              {attachmentCount}
            </span>
          </div>
          <DocumentsTab
            entityType="SERVICE_CALL"
            entityId={serviceCall.id}
            onCountChange={setAttachmentCount}
          />
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <div className="mb-6 flex items-center gap-3">
            <h3 className="text-xl font-bold text-slate-900">Activity</h3>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-600">
              {activityCount}
            </span>
          </div>
          <ActivityTimeline
            entityType="SERVICE_CALL"
            entityId={serviceCall.id}
            onCountChange={setActivityCount}
          />
        </div>
      </div>
      {/* Customer Satisfaction — recorded once, at the very end of the journey */}
      {serviceCall.status === "CLOSED" && (
        <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <h3 className="mb-1 text-xl font-bold text-slate-900">Customer Satisfaction</h3>
          <p className="mb-6 text-sm text-slate-500">
            Feedback on the whole service journey, captured at close-out.
          </p>

          {satisfaction ? (
            <div className="rounded-xl border border-green-200 bg-green-50 p-5">
              <p className="text-lg font-semibold text-green-700">
                {satisfaction.rating} / 5
              </p>
              {satisfaction.feedback && (
                <p className="mt-2 text-sm text-slate-600">{satisfaction.feedback}</p>
              )}
              <p className="mt-2 text-xs text-slate-400">
                {satisfaction.wouldRecommend ? "Would recommend us" : "Would not recommend us"}
                {" • "}
                {formatDate(satisfaction.recordedAt)}
              </p>
            </div>
          ) : (
            <div className="space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-5">
              <div className="flex items-center gap-3">
                <label className="text-sm font-medium text-slate-700">Rating:</label>
                <select
                  value={satForm.rating}
                  onChange={(e) => setSatForm({ ...satForm, rating: e.target.value })}
                  className="rounded-lg border border-slate-200 px-3 py-1.5 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                >
                  {[5, 4, 3, 2, 1].map((n) => (
                    <option key={n} value={n}>
                      {n} / 5
                    </option>
                  ))}
                </select>
                <label className="ml-4 flex items-center gap-2 text-sm text-slate-700">
                  <input
                    type="checkbox"
                    checked={satForm.wouldRecommend}
                    onChange={(e) =>
                      setSatForm({ ...satForm, wouldRecommend: e.target.checked })
                    }
                  />
                  Would recommend us
                </label>
              </div>
              <textarea
                placeholder="How did the whole experience feel?"
                value={satForm.feedback}
                onChange={(e) => setSatForm({ ...satForm, feedback: e.target.value })}
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
                rows={2}
              />
              <button
                disabled={savingSat}
                onClick={submitSatisfaction}
                className="rounded-xl bg-[#1296E8] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
              >
                Save Feedback
              </button>
            </div>
          )}
        </div>
      )}
    </DashboardLayout>
  );
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <h3 className="mb-5 text-lg font-bold">{title}</h3>
      {children}
    </div>
  );
}

function Info({ label, value }: { label: string; value?: string }) {
  return (
    <div className="mb-4">
      <p className="text-xs font-semibold uppercase tracking-wide text-slate-400">
        {label}
      </p>
      <p className="mt-1 font-medium text-slate-900">{value || "—"}</p>
    </div>
  );
}

function Badge({ value }: { value: string }) {
  const color =
    value === "CRITICAL" ? "bg-red-100 text-red-700"
    : value === "HIGH" ? "bg-orange-100 text-orange-700"
    : value === "OPEN" ? "bg-yellow-100 text-yellow-700"
    : value === "IN_PROGRESS" ? "bg-blue-100 text-blue-700"
    : value === "COMPLETED" ? "bg-purple-100 text-purple-700"
    : value === "CLOSED" ? "bg-green-100 text-green-700"
    : value === "FIELD_SERVICE" ? "bg-[#1296E8]/10 text-[#1296E8]"
    : value === "WORKSHOP_SERVICE" ? "bg-indigo-100 text-indigo-700"
    : value === "DEMONSTRATION" ? "bg-teal-100 text-teal-700"
    : "bg-slate-100 text-slate-600";

  return (
    <span className={`rounded-full px-4 py-2 text-sm font-semibold ${color}`}>
      {value}
    </span>
  );
}