"use client";

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

interface Part {
  id: number;
  partCode: string;
  name: string;
  unit: string;
  unitPrice: number;
  stockQuantity: number;
}

interface PartUsed {
  id: number;
  part: Part;
  quantity: number;
  unitPriceAtUse: number;
  notes: string;
  createdAt: string;
}

interface Props {
  serviceCallId: number;
  onCountChange?: (count: number) => void;
}

export default function PartsUsedSection({ serviceCallId, onCountChange }: Props) {
  const [partsUsed, setPartsUsed] = useState<PartUsed[]>([]);
  const [allParts, setAllParts] = useState<Part[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [selectedPartId, setSelectedPartId] = useState("");
  const [quantity, setQuantity] = useState("1");
  const [notes, setNotes] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);

  function loadPartsUsed() {
    fetch(`${API_URL}/api/parts-used/service-call/${serviceCallId}`)
      .then((res) => res.json())
      .then((data) => {
        setPartsUsed(data);
        onCountChange?.(data.length);
      })
      .catch(console.error);
  }

  function loadAllParts() {
    fetch(`${API_URL}/api/parts`)
      .then((res) => res.json())
      .then(setAllParts)
      .catch(console.error);
  }

  useEffect(() => {
    loadPartsUsed();
    loadAllParts();
  }, [serviceCallId]);

  const selectedPart = allParts.find((p) => String(p.id) === selectedPartId);

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

    if (!selectedPartId) {
      setError("Please select a part.");
      return;
    }

    const qty = Number(quantity);
    if (!qty || qty < 1) {
      setError("Quantity must be at least 1.");
      return;
    }

    if (selectedPart && selectedPart.stockQuantity != null && qty > selectedPart.stockQuantity) {
      setError(`Only ${selectedPart.stockQuantity} ${selectedPart.unit} in stock.`);
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch(
        `${API_URL}/api/parts-used/service-call/${serviceCallId}/part/${selectedPartId}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ quantity: qty, notes }),
        }
      );

      if (res.ok) {
        setSelectedPartId("");
        setQuantity("1");
        setNotes("");
        setShowForm(false);
        loadPartsUsed();
        loadAllParts();
      } else {
        setError("Failed to add part. Please try again.");
      }
    } catch {
      setError("Network error. Is the backend running?");
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: number) {
    await fetch(`${API_URL}/api/parts-used/${id}`, { method: "DELETE" });
    loadPartsUsed();
    loadAllParts();
  }

  const totalCost = partsUsed.reduce(
    (sum, pu) => sum + (pu.unitPriceAtUse || 0) * pu.quantity,
    0
  );

  return (
    <div>
      {partsUsed.length === 0 ? (
        <div className="rounded-xl border border-dashed border-slate-300 p-8 text-center text-slate-500">
          No parts used yet.
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-slate-200">
          <table className="w-full text-sm">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Part</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Qty</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Unit Price</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Total</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {partsUsed.map((pu) => (
                <tr key={pu.id} className="border-t border-slate-100">
                  <td className="px-4 py-3">
                    <div className="font-medium text-slate-900">{pu.part?.name}</div>
                    <div className="text-xs text-slate-400">{pu.part?.partCode}</div>
                  </td>
                  <td className="px-4 py-3">
                    {pu.quantity} {pu.part?.unit}
                  </td>
                  <td className="px-4 py-3">AED {pu.unitPriceAtUse?.toFixed(2) ?? "0.00"}</td>
                  <td className="px-4 py-3 font-medium">
                    AED {((pu.unitPriceAtUse || 0) * pu.quantity).toFixed(2)}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => handleDelete(pu.id)}
                      className="text-xs font-semibold text-red-600 hover:underline"
                    >
                      Remove
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="border-t border-slate-200 bg-slate-50">
                <td colSpan={3} className="px-4 py-3 text-right font-semibold text-slate-700">
                  Total
                </td>
                <td className="px-4 py-3 font-bold text-slate-900">
                  AED {totalCost.toFixed(2)}
                </td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}

      {!showForm ? (
        <button
          onClick={() => setShowForm(true)}
          className="mt-4 rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:border-[#1296E8] hover:text-[#1296E8]"
        >
          + Add Part
        </button>
      ) : (
        <form
          onSubmit={handleAdd}
          className="mt-4 rounded-xl border border-slate-200 bg-slate-50 p-5"
        >
          {error && (
            <div className="mb-3 rounded-lg bg-red-50 px-3 py-2 text-xs font-medium text-red-700">
              {error}
            </div>
          )}

          <div className="grid grid-cols-3 gap-3">
            <div className="col-span-2">
              <label className="mb-1 block text-xs font-medium text-slate-600">Part</label>
              <select
                value={selectedPartId}
                onChange={(e) => setSelectedPartId(e.target.value)}
                className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              >
                <option value="">Select part...</option>
                {allParts.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name} ({p.partCode}) — Stock: {p.stockQuantity} {p.unit}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="mb-1 block text-xs font-medium text-slate-600">Quantity</label>
              <input
                type="number"
                min={1}
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
                className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
            </div>
          </div>

          <div className="mt-3">
            <label className="mb-1 block text-xs font-medium text-slate-600">Notes (optional)</label>
            <input
              type="text"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="e.g. Replaced under warranty"
              className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
            />
          </div>

          <div className="mt-4 flex justify-end gap-2">
            <button
              type="button"
              onClick={() => {
                setShowForm(false);
                setError("");
              }}
              className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="rounded-lg bg-[#EE302B] px-4 py-2 text-sm font-semibold text-white disabled:opacity-60"
            >
              {submitting ? "Adding..." : "Add Part"}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}