"use client";

import {useState, useTransition} from "react";
import {createContract} from "@/features/contracts/server/actions";
import {Button} from "@/components/ui/button";

type NewContractPageClientProps = {
  tenantId: string;
  tenantSlug: string;
  currency: string;
  bookings: Array<{
    id: string;
    bookingNumber: string;
    customerName: string;
    vehicleName: string;
    vehiclePlate: string;
    pickupAt: Date;
    dropoffAt: Date;
    dailyRate: number;
    totalAmount: number;
    depositAmount: number;
    pickupLocation: string;
    dropoffLocation: string;
  }>;
};

export function NewContractForm({tenantId, tenantSlug, currency, bookings}: NewContractPageClientProps) {
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const [selectedBookingId, setSelectedBookingId] = useState("");

  const selectedBooking = bookings.find((b) => b.id === selectedBookingId);

  function handleBookingChange(id: string) {
    setSelectedBookingId(id);
  }

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);
    startTransition(async () => {
      const result = await createContract(fd);
      if (!result.success) setError(result.error ?? "Unknown error");
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      <input type="hidden" name="tenantId" value={tenantId} />

      {/* Select Booking */}
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-700">Link to Booking</h2>
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Select Booking *</label>
            <select
              name="bookingId"
              required
              value={selectedBookingId}
              onChange={(e) => handleBookingChange(e.target.value)}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            >
              <option value="">— Choose a booking —</option>
              {bookings.map((b) => (
                <option key={b.id} value={b.id}>
                  {b.bookingNumber} — {b.customerName} — {b.vehicleName}
                </option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Contract Number *</label>
              <input
                name="contractNumber"
                required
                defaultValue={`CTR-${Date.now().toString().slice(-6)}`}
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm font-mono outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
          </div>
        </div>
      </section>

      {/* Customer Info */}
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-700">Customer Information</h2>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Full Name *</label>
            <input
              name="customerName"
              required
              defaultValue={selectedBooking?.customerName ?? ""}
              key={`customerName-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Phone *</label>
            <input
              name="customerPhone"
              required
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">ID / Passport Number *</label>
            <input
              name="customerIdNumber"
              required
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Driver License Number *</label>
            <input
              name="licenseNumber"
              required
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">License Expiry *</label>
            <input
              name="licenseExpiry"
              type="date"
              required
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
        </div>
      </section>

      {/* Vehicle & Rental */}
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-700">Vehicle & Rental Details</h2>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Vehicle Name *</label>
            <input
              name="vehicleName"
              required
              defaultValue={selectedBooking?.vehicleName ?? ""}
              key={`vehicleName-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Plate Number *</label>
            <input
              name="vehiclePlate"
              required
              defaultValue={selectedBooking?.vehiclePlate ?? ""}
              key={`vehiclePlate-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm font-mono outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Pickup Location *</label>
            <input
              name="pickupLocation"
              required
              defaultValue={selectedBooking?.pickupLocation ?? ""}
              key={`pickupLocation-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Dropoff Location *</label>
            <input
              name="dropoffLocation"
              required
              defaultValue={selectedBooking?.dropoffLocation ?? ""}
              key={`dropoffLocation-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Pickup Date *</label>
            <input
              name="pickupDate"
              type="datetime-local"
              required
              defaultValue={selectedBooking?.pickupAt ? new Date(selectedBooking.pickupAt).toISOString().slice(0, 16) : ""}
              key={`pickupDate-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Return Date *</label>
            <input
              name="dropoffDate"
              type="datetime-local"
              required
              defaultValue={selectedBooking?.dropoffAt ? new Date(selectedBooking.dropoffAt).toISOString().slice(0, 16) : ""}
              key={`dropoffDate-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Daily Rate ({currency}) *</label>
            <input
              name="dailyRate"
              type="number"
              step="0.01"
              required
              defaultValue={selectedBooking?.dailyRate ?? ""}
              key={`dailyRate-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Total Amount ({currency}) *</label>
            <input
              name="totalAmount"
              type="number"
              step="0.01"
              required
              defaultValue={selectedBooking?.totalAmount ?? ""}
              key={`totalAmount-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Deposit Amount ({currency}) *</label>
            <input
              name="depositAmount"
              type="number"
              step="0.01"
              required
              defaultValue={selectedBooking?.depositAmount ?? ""}
              key={`depositAmount-${selectedBookingId}`}
              className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
            />
          </div>
          <div className="flex items-center gap-3 pt-6">
            <input
              type="checkbox"
              name="insuranceIncluded"
              id="insuranceIncluded"
              className="h-4 w-4"
            />
            <label htmlFor="insuranceIncluded" className="text-sm font-medium text-slate-700">Insurance Included</label>
          </div>
        </div>
      </section>

      {/* Notes */}
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-700">Notes & Terms</h2>
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Notes</label>
            <textarea
              name="notes"
              rows={3}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              placeholder="Any special notes..."
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">Terms & Conditions</label>
            <textarea
              name="terms"
              rows={4}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              placeholder="Standard terms and conditions..."
            />
          </div>
        </div>
      </section>

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

      <div className="flex gap-3">
        <Button type="submit" disabled={isPending} className="bg-blue-600 hover:bg-blue-700">
          {isPending ? "Creating..." : "Create Contract"}
        </Button>
        <a
          href={`/company/${tenantSlug}/contracts`}
          className="rounded-lg border border-slate-200 px-6 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
        >
          Cancel
        </a>
      </div>
    </form>
  );
}
