"use client";

import {useState} from "react";
import {useRouter} from "next/navigation";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {Select} from "@/components/ui/select";
import {Textarea} from "@/components/ui/textarea";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {ArrowLeft} from "lucide-react";
import {createVehicle} from "@/features/vehicles/server/actions";

type Branch = {id: string; name: string};
type Model = {id: string; name: string};
type Brand = {id: string; name: string; models: Model[]};

type NewVehicleFormProps = {
  tenantSlug: string;
  branches: Branch[];
  brands: Brand[];
};

export function NewVehicleForm({tenantSlug, branches, brands}: NewVehicleFormProps) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isPending, setIsPending] = useState(false);
  const [selectedBrandId, setSelectedBrandId] = useState(brands[0]?.id ?? "");

  const currentBrand = brands.find((b) => b.id === selectedBrandId);
  const models = currentBrand?.models ?? [];

  async function handleSubmit(formData: FormData) {
    setError(null);
    setIsPending(true);
    formData.set("tenantSlug", tenantSlug);
    try {
      await createVehicle(formData);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Unknown error";
      if (!message.includes("NEXT_REDIRECT")) {
        setError(message);
      }
    } finally {
      setIsPending(false);
    }
  }

  return (
    <div className="max-w-2xl space-y-6">
      <div className="flex items-center gap-3">
        <button onClick={() => router.back()} className="flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 transition">
          <ArrowLeft className="h-4 w-4" />
          Back
        </button>
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Add New Vehicle</h1>
        </div>
      </div>

      <form action={handleSubmit} className="space-y-6">
        {/* Basic Info */}
        <Card>
          <CardHeader><CardTitle>Basic Information</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="name">Vehicle Name *</Label>
              <Input id="name" name="name" className="mt-1" placeholder="e.g. Toyota Camry 2023" required />
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <Label htmlFor="brandId">Brand *</Label>
                <Select
                  id="brandId"
                  name="brandId"
                  className="mt-1"
                  value={selectedBrandId}
                  onChange={(e) => setSelectedBrandId(e.target.value)}
                  required
                >
                  {brands.map((b) => (
                    <option key={b.id} value={b.id}>{b.name}</option>
                  ))}
                </Select>
              </div>
              <div>
                <Label htmlFor="modelId">Model *</Label>
                <Select id="modelId" name="modelId" className="mt-1" required>
                  {models.map((m) => (
                    <option key={m.id} value={m.id}>{m.name}</option>
                  ))}
                </Select>
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-3">
              <div>
                <Label htmlFor="year">Year *</Label>
                <Input id="year" name="year" type="number" className="mt-1" defaultValue={new Date().getFullYear()} required />
              </div>
              <div>
                <Label htmlFor="plateNumber">Plate Number *</Label>
                <Input id="plateNumber" name="plateNumber" className="mt-1" required />
              </div>
              <div>
                <Label htmlFor="color">Color</Label>
                <Input id="color" name="color" className="mt-1" />
              </div>
            </div>
            <div>
              <Label htmlFor="vin">VIN *</Label>
              <Input id="vin" name="vin" className="mt-1" required />
            </div>
          </CardContent>
        </Card>

        {/* Specs */}
        <Card>
          <CardHeader><CardTitle>Specifications</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <Label htmlFor="category">Category *</Label>
                <Select id="category" name="category" className="mt-1" defaultValue="SEDAN" required>
                  {["ECONOMY", "SEDAN", "SUV", "LUXURY", "SPORT", "VAN", "PICKUP"].map((c) => (
                    <option key={c} value={c}>{c}</option>
                  ))}
                </Select>
              </div>
              <div>
                <Label htmlFor="transmission">Transmission *</Label>
                <Select id="transmission" name="transmission" className="mt-1" defaultValue="AUTOMATIC" required>
                  <option value="AUTOMATIC">Automatic</option>
                  <option value="MANUAL">Manual</option>
                </Select>
              </div>
              <div>
                <Label htmlFor="fuelType">Fuel Type *</Label>
                <Select id="fuelType" name="fuelType" className="mt-1" defaultValue="PETROL" required>
                  <option value="PETROL">Petrol</option>
                  <option value="DIESEL">Diesel</option>
                  <option value="HYBRID">Hybrid</option>
                  <option value="ELECTRIC">Electric</option>
                </Select>
              </div>
              <div>
                <Label htmlFor="seats">Seats *</Label>
                <Input id="seats" name="seats" type="number" className="mt-1" defaultValue={5} min={1} max={20} required />
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-3">
              <div>
                <Label htmlFor="doors">Doors</Label>
                <Input id="doors" name="doors" type="number" className="mt-1" defaultValue={4} min={2} max={6} />
              </div>
              <div>
                <Label htmlFor="bags">Bags</Label>
                <Input id="bags" name="bags" type="number" className="mt-1" defaultValue={2} min={0} />
              </div>
              <div>
                <Label htmlFor="mileage">Mileage (km)</Label>
                <Input id="mileage" name="mileage" type="number" className="mt-1" defaultValue={0} min={0} />
              </div>
            </div>
            <div className="flex flex-wrap gap-4">
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="airConditioning" defaultChecked className="h-4 w-4 rounded" />
                Air Conditioning
              </label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="hasGps" className="h-4 w-4 rounded" />
                GPS
              </label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="hasBluetooth" defaultChecked className="h-4 w-4 rounded" />
                Bluetooth
              </label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="insuranceIncluded" className="h-4 w-4 rounded" />
                Insurance Included
              </label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="isPublic" defaultChecked className="h-4 w-4 rounded" />
                Public Listing
              </label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input type="checkbox" name="featured" className="h-4 w-4 rounded" />
                Featured
              </label>
            </div>
          </CardContent>
        </Card>

        {/* Pricing */}
        <Card>
          <CardHeader><CardTitle>Pricing & Branch</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <Label htmlFor="dailyRate">Daily Rate *</Label>
                <Input id="dailyRate" name="dailyRate" type="number" step="0.01" className="mt-1" defaultValue={0} min={0} required />
              </div>
              <div>
                <Label htmlFor="depositAmount">Deposit Amount *</Label>
                <Input id="depositAmount" name="depositAmount" type="number" step="0.01" className="mt-1" defaultValue={0} min={0} required />
              </div>
              <div>
                <Label htmlFor="weeklyRate">Weekly Rate</Label>
                <Input id="weeklyRate" name="weeklyRate" type="number" step="0.01" className="mt-1" defaultValue={0} min={0} />
              </div>
              <div>
                <Label htmlFor="monthlyRate">Monthly Rate</Label>
                <Input id="monthlyRate" name="monthlyRate" type="number" step="0.01" className="mt-1" defaultValue={0} min={0} />
              </div>
            </div>
            <div>
              <Label htmlFor="branchId">Branch *</Label>
              <Select id="branchId" name="branchId" className="mt-1" required>
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>{b.name}</option>
                ))}
              </Select>
            </div>
            <div>
              <Label htmlFor="primaryImageUrl">Image URL</Label>
              <Input id="primaryImageUrl" name="primaryImageUrl" className="mt-1" placeholder="https://..." />
            </div>
          </CardContent>
        </Card>

        {/* Description */}
        <Card>
          <CardHeader><CardTitle>Description</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="descriptionEn">Description (English)</Label>
              <Textarea id="descriptionEn" name="descriptionEn" className="mt-1" rows={3} />
            </div>
            <div>
              <Label htmlFor="descriptionAr">Description (Arabic)</Label>
              <Textarea id="descriptionAr" name="descriptionAr" className="mt-1" rows={3} dir="rtl" />
            </div>
          </CardContent>
        </Card>

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

        <div className="flex gap-3">
          <Button type="button" variant="outline" onClick={() => router.back()}>Cancel</Button>
          <Button type="submit" disabled={isPending} className="flex-1 max-w-xs">
            {isPending ? "Saving..." : "Save Vehicle"}
          </Button>
        </div>
      </form>
    </div>
  );
}
