"use client";

import { useCallback, useEffect, useRef, 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 {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { RichTextEditor } from "@/components/shared/rich-text-editor";
import {
  ArrowLeft,
  Save,
  MapPin,
  Car,
  Plus,
  Trash2,
  Route,
  Check,
  ChevronsUpDown,
  X,
} from "lucide-react";
import { getAllCitiesAction } from "@/features/locations/actions/cities-actions";
import {
  getVehiclesAction,
  type VehicleListItem,
} from "@/features/vehicles/actions/vehicles-actions";
import {
  createRouteAction,
  updateRouteAction,
  getRouteAction,
  type MultiCityStop,
} from "@/features/routes/actions/routes-actions";
import type { City } from "@/core/api";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";

interface RouteFormProps {
  routeId?: string;
}

type RouteType = "one_way" | "round_trip" | "multi_city";
type StatusType = "active" | "inactive";

interface StopageEntry {
  tempId: string;
  stopage_city_id: string;
  distance_from_previous_stopage: string;
  duration_from_previouse_stopage: string;
  sort_order: number;
  status: StatusType;
  description: string;
}

export function RouteForm({ routeId }: RouteFormProps) {
  const router = useRouter();
  const toast = useToastEnhanced();
  const isEditing = Boolean(routeId);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const [descriptionValue, setDescriptionValue] = useState("");

  const [cities, setCities] = useState<City[]>([]);
  const [vehicles, setVehicles] = useState<VehicleListItem[]>([]);
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Form state
  const [name, setName] = useState("");
  const [startCityId, setStartCityId] = useState("");
  const [endCityId, setEndCityId] = useState("");
  const [routeType, setRouteType] = useState<RouteType>("one_way");
  const [totalDistance, setTotalDistance] = useState("");
  const [totalDuration, setTotalDuration] = useState("");
  const [totalPrice, setTotalPrice] = useState("");
  const [discountPrice, setDiscountPrice] = useState("");
  const [status, setStatus] = useState<StatusType>("active");
  const [assignedVehicleIds, setAssignedVehicleIds] = useState<number[]>([]);
  const [stopages, setStopages] = useState<StopageEntry[]>([]);

  useEffect(() => {
    const loadData = async () => {
      setIsLoadingData(true);

      const requests: [
        ReturnType<typeof getAllCitiesAction>,
        ReturnType<typeof getVehiclesAction>,
        ReturnType<typeof getRouteAction>?,
      ] = routeId
        ? [
            getAllCitiesAction(),
            getVehiclesAction(1, 1000, "active"),
            getRouteAction(Number(routeId)),
          ]
        : [getAllCitiesAction(), getVehiclesAction(1, 1000, "active")];

      const [citiesResult, vehiclesResult, routeResult] =
        await Promise.all(requests);

      if (citiesResult.success && citiesResult.data)
        setCities(citiesResult.data);
      if (vehiclesResult.success && vehiclesResult.data)
        setVehicles(vehiclesResult.data.data);

      if (routeResult?.success && routeResult.data) {
        const r = routeResult.data;
        setName(r.name);
        setStartCityId(r.start_point_city_id.toString());
        setEndCityId(r.end_point_city_id.toString());
        setRouteType(r.route_type);
        setTotalDistance(r.total_distance ?? "");
        setTotalDuration(r.total_duration ?? "");
        setTotalPrice(r.total_price?.toString() ?? "");
        setDiscountPrice(r.discount_price?.toString() ?? "");
        setStatus((r.status as StatusType) ?? "active");
        setDescriptionValue(r.description ?? "");

        if (r.assigned_vehicles && Array.isArray(r.assigned_vehicles)) {
          setAssignedVehicleIds(r.assigned_vehicles.map((v) => v.id));
        }

        if (r.route_type === "multi_city" && r.multi_cities?.length) {
          setStopages(
            r.multi_cities
              .slice()
              .sort((a, b) => a.sort_order - b.sort_order)
              .map((s, i) => ({
                tempId: `stop_${s.id ?? i}`,
                stopage_city_id: s.stopage_city_id.toString(),
                distance_from_previous_stopage:
                  s.distance_from_previous_stopage?.toString() ?? "",
                duration_from_previouse_stopage:
                  s.duration_from_previouse_stopage ?? "",
                sort_order: s.sort_order,
                status: (s.status as StatusType) ?? "active",
                description: s.description ?? "",
              }))
          );
        }
      } else if (routeResult && !routeResult.success) {
        toast.error({
          title: "Failed to load route",
          description: routeResult.error,
        });
      }

      setIsLoadingData(false);
    };
    loadData();
  }, [routeId]);

  const toggleVehicle = useCallback((id: number) => {
    setAssignedVehicleIds((prev) =>
      prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]
    );
  }, []);

  const addStopage = useCallback(() => {
    setStopages((prev) => [
      ...prev,
      {
        tempId: `stop_${Date.now()}`,
        stopage_city_id: "",
        distance_from_previous_stopage: "",
        duration_from_previouse_stopage: "",
        sort_order: prev.length + 1,
        status: "active",
        description: "",
      },
    ]);
  }, []);

  const removeStopage = useCallback((tempId: string) => {
    setStopages((prev) =>
      prev
        .filter((s) => s.tempId !== tempId)
        .map((s, i) => ({ ...s, sort_order: i + 1 }))
    );
  }, []);

  const updateStopage = useCallback(
    (tempId: string, field: keyof StopageEntry, value: string) => {
      setStopages((prev) =>
        prev.map((s) => (s.tempId === tempId ? { ...s, [field]: value } : s))
      );
    },
    []
  );

  const handleSubmit = async () => {
    if (!name.trim()) {
      toast.error({
        title: "Route Name Required",
        description: "Please enter a route name.",
      });
      return;
    }
    if (!startCityId) {
      toast.error({
        title: "Start City Required",
        description: "Please select a starting city.",
      });
      return;
    }
    if (!endCityId) {
      toast.error({
        title: "End City Required",
        description: "Please select a destination city.",
      });
      return;
    }
    if (startCityId === endCityId) {
      toast.error({
        title: "Invalid Route",
        description: "Start and end cities cannot be the same.",
      });
      return;
    }
    if (routeType === "multi_city" && stopages.length === 0) {
      toast.error({
        title: "Stopage Required",
        description: "Add at least one stopage city for multi-city routes.",
      });
      return;
    }
    if (routeType === "multi_city") {
      const missing = stopages.some((s) => !s.stopage_city_id);
      if (missing) {
        toast.error({
          title: "Incomplete Stopage",
          description: "Please select a city for all stopage entries.",
        });
        return;
      }
    }

    const description =
      descriptionRef.current?.querySelector(".ql-editor")?.innerHTML?.trim() ||
      "";

    setIsSubmitting(true);

    const multiCities: MultiCityStop[] = stopages.map((s) => ({
      stopage_city_id: Number(s.stopage_city_id),
      distance_from_previous_stopage: s.distance_from_previous_stopage
        ? Number(s.distance_from_previous_stopage)
        : null,
      duration_from_previouse_stopage:
        s.duration_from_previouse_stopage || null,
      sort_order: s.sort_order,
      status: s.status,
      description: s.description || null,
    }));

    const payload = {
      name: name.trim(),
      start_point_city_id: Number(startCityId),
      end_point_city_id: Number(endCityId),
      route_type: routeType,
      total_distance: totalDistance ? Number(totalDistance) : null,
      total_duration: totalDuration.trim() || null,
      total_price: totalPrice ? Number(totalPrice) : null,
      discount_price: discountPrice ? Number(discountPrice) : null,
      status,
      description: description || null,
      assign_vehicle_ids: assignedVehicleIds,
      multi_cities: routeType === "multi_city" ? multiCities : undefined,
    };

    const result =
      isEditing && routeId
        ? await updateRouteAction(Number(routeId), payload)
        : await createRouteAction(payload);

    setIsSubmitting(false);

    if (result.success) {
      toast.success({
        title: isEditing ? "Route Updated" : "Route Created",
        description: `The route has been ${isEditing ? "updated" : "created"} successfully.`,
      });
      router.push("/admin/routes-listing");
    } else {
      toast.error({
        title: isEditing ? "Failed to Update Route" : "Failed to Create Route",
        description: result.error || "Something went wrong.",
      });
    }
  };

  const totalPriceNumber = Number(totalPrice);
  const discountPriceNumber = Number(discountPrice);
  const discountPercent =
    totalPriceNumber > 0 &&
    discountPriceNumber > 0 &&
    discountPriceNumber < totalPriceNumber
      ? Math.round(
          ((totalPriceNumber - discountPriceNumber) / totalPriceNumber) * 100
        )
      : 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => router.back()}
          aria-label="Go back"
        >
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">
            {isEditing ? "Edit Route" : "Add New Route"}
          </h1>
          <p className="text-muted-foreground">
            {isEditing ? "Update route details" : "Create a new vehicle route"}
          </p>
        </div>
      </div>

      {/* Route Information */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Route className="h-5 w-5 text-primary" />
                Route Information
              </CardTitle>
              <CardDescription>Basic details about this route</CardDescription>
            </div>
            <div className="space-y-1 text-right">
              <Label htmlFor="status">Status *</Label>
              <Select
                value={status}
                onValueChange={(v) => setStatus(v as StatusType)}
              >
                <SelectTrigger id="status" className="w-36">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="route-name">Route Name *</Label>
            <Input
              id="route-name"
              placeholder="e.g. Ahmedabad to Vadodara"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-3">
            <div className="space-y-2">
              <Label htmlFor="start-city">Starting City *</Label>
              <Select
                value={startCityId}
                onValueChange={setStartCityId}
                disabled={isLoadingData}
              >
                <SelectTrigger id="start-city">
                  <SelectValue
                    placeholder={
                      isLoadingData ? "Loading cities…" : "Select starting city"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {cities.map((city) => (
                    <SelectItem
                      key={city.id}
                      value={city.id.toString()}
                      disabled={city.id.toString() === endCityId}
                    >
                      {city.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="end-city">Destination City *</Label>
              <Select
                value={endCityId}
                onValueChange={setEndCityId}
                disabled={isLoadingData}
              >
                <SelectTrigger id="end-city">
                  <SelectValue
                    placeholder={
                      isLoadingData
                        ? "Loading cities…"
                        : "Select destination city"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {cities.map((city) => (
                    <SelectItem
                      key={city.id}
                      value={city.id.toString()}
                      disabled={city.id.toString() === startCityId}
                    >
                      {city.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="route-type">Route Type *</Label>
              <Select
                value={routeType}
                onValueChange={(v) => setRouteType(v as RouteType)}
              >
                <SelectTrigger id="route-type">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="one_way">One Way</SelectItem>
                  <SelectItem value="round_trip">Round Trip</SelectItem>
                  <SelectItem value="multi_city">Multi City</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="total-distance">Total Distance (km)</Label>
              <Input
                id="total-distance"
                type="number"
                min={0}
                step={0.1}
                placeholder="e.g. 110.5"
                value={totalDistance}
                onChange={(e) => setTotalDistance(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="total-duration">Total Duration</Label>
              <Input
                id="total-duration"
                placeholder="e.g. 2h 10m"
                value={totalDuration}
                onChange={(e) => setTotalDuration(e.target.value)}
              />
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="total-price">Total Price (INR)</Label>
              <Input
                id="total-price"
                type="number"
                min={0}
                step={1}
                placeholder="e.g. 5000"
                value={totalPrice}
                onChange={(e) => setTotalPrice(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="discount-price">Discount Price (INR)</Label>
              <div className="relative">
                <Input
                  id="discount-price"
                  type="number"
                  min={0}
                  step={1}
                  placeholder="e.g. 4500"
                  value={discountPrice}
                  onChange={(e) => setDiscountPrice(e.target.value)}
                />
                {discountPercent > 0 ? (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full border border-green-200 bg-green-50 px-2 py-0.5 text-xs font-medium text-green-600">
                    {discountPercent}% OFF
                  </div>
                ) : null}
              </div>
            </div>
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <RichTextEditor
              value={descriptionValue}
              onChange={setDescriptionValue}
              placeholder="Enter route description…"
              editorRef={descriptionRef}
            />
          </div>
        </CardContent>
      </Card>

      {/* Stopage Cities — only for multi_city */}
      {routeType === "multi_city" && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <MapPin className="h-5 w-5 text-primary" />
                  Stopage Cities
                </CardTitle>
                <CardDescription>
                  Add intermediate stops between start and end cities
                </CardDescription>
              </div>
              <Button type="button" size="sm" onClick={addStopage}>
                <Plus className="mr-2 h-4 w-4" />
                Add Stopage
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            {stopages.length === 0 ? (
              <p className="text-center text-sm text-muted-foreground py-4">
                No stopages added yet. Click &quot;Add Stopage&quot; to add one.
              </p>
            ) : (
              stopages.map((stop, index) => (
                <div
                  key={stop.tempId}
                  className="rounded-lg border p-4 space-y-4"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">
                      Stop {index + 1}
                    </span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeStopage(stop.tempId)}
                      className="h-8 w-8 text-destructive hover:text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>

                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label>Stopage City *</Label>
                      <Select
                        value={stop.stopage_city_id}
                        onValueChange={(v) =>
                          updateStopage(stop.tempId, "stopage_city_id", v)
                        }
                        disabled={isLoadingData}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select city" />
                        </SelectTrigger>
                        <SelectContent>
                          {cities.map((city) => (
                            <SelectItem
                              key={city.id}
                              value={city.id.toString()}
                            >
                              {city.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Status</Label>
                      <Select
                        value={stop.status}
                        onValueChange={(v) =>
                          updateStopage(stop.tempId, "status", v)
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="active">Active</SelectItem>
                          <SelectItem value="inactive">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Distance from Previous Stop (km)</Label>
                      <Input
                        type="number"
                        min={0}
                        step={0.1}
                        placeholder="e.g. 140"
                        value={stop.distance_from_previous_stopage}
                        onChange={(e) =>
                          updateStopage(
                            stop.tempId,
                            "distance_from_previous_stopage",
                            e.target.value
                          )
                        }
                      />
                    </div>

                    <div className="space-y-2">
                      <Label>Duration from Previous Stop</Label>
                      <Input
                        placeholder="e.g. 2h 45m"
                        value={stop.duration_from_previouse_stopage}
                        onChange={(e) =>
                          updateStopage(
                            stop.tempId,
                            "duration_from_previouse_stopage",
                            e.target.value
                          )
                        }
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Description</Label>
                    <RichTextEditor
                      value={stop.description}
                      onChange={(v) =>
                        updateStopage(stop.tempId, "description", v)
                      }
                      placeholder="Optional note about this stop…"
                    />
                  </div>
                </div>
              ))
            )}
          </CardContent>
        </Card>
      )}

      {/* Assign Vehicles */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Car className="h-5 w-5 text-primary" />
            Assign Vehicles
          </CardTitle>
          <CardDescription>
            {assignedVehicleIds.length > 0
              ? `${assignedVehicleIds.length} vehicle(s) selected`
              : "Select vehicles to assign to this route"}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <Popover>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                role="combobox"
                disabled={isLoadingData}
                className="w-full justify-between font-normal"
              >
                {isLoadingData
                  ? "Loading vehicles…"
                  : assignedVehicleIds.length > 0
                    ? `${assignedVehicleIds.length} vehicle(s) selected`
                    : "Select vehicles…"}
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-full p-0" align="start">
              <Command>
                <CommandInput placeholder="Search vehicles…" />
                <CommandList>
                  <CommandEmpty>No vehicles found.</CommandEmpty>
                  <CommandGroup>
                    {vehicles.map((vehicle) => {
                      const selected = assignedVehicleIds.includes(vehicle.id);
                      return (
                        <CommandItem
                          key={vehicle.id}
                          value={vehicle.name}
                          onSelect={() => toggleVehicle(vehicle.id)}
                        >
                          <Check
                            className={`mr-2 h-4 w-4 ${selected ? "opacity-100" : "opacity-0"}`}
                          />
                          <span className="flex-1">{vehicle.name}</span>
                          <span className="text-xs text-muted-foreground">
                            {vehicle.category?.name ?? vehicle.fuel_type}
                          </span>
                        </CommandItem>
                      );
                    })}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>

          {assignedVehicleIds.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {assignedVehicleIds.map((id) => {
                const vehicle = vehicles.find((v) => v.id === id);
                if (!vehicle) return null;
                return (
                  <Badge key={id} variant="secondary" className="gap-1 pr-1">
                    {vehicle.name}
                    <button
                      type="button"
                      onClick={() => toggleVehicle(id)}
                      className="ml-1 rounded-full hover:bg-muted"
                      aria-label={`Remove ${vehicle.name}`}
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Actions */}
      <div className="flex items-center justify-end gap-4">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.back()}
          disabled={isSubmitting}
        >
          Cancel
        </Button>
        <Button onClick={handleSubmit} disabled={isSubmitting || isLoadingData}>
          <Save className="mr-2 h-4 w-4" />
          {isSubmitting
            ? "Saving…"
            : isEditing
              ? "Update Route"
              : "Create Route"}
        </Button>
      </div>
    </div>
  );
}
