"use client";

import type React from "react";

import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import {
  BedDouble,
  Plus,
  Edit2,
  Trash2,
  Users,
  IndianRupee,
  Wifi,
  AirVent,
  Tv,
  Coffee,
  Car,
  UtensilsCrossed,
  Dumbbell,
  Bath,
  Upload,
  X,
  ImageIcon,
} from "lucide-react";

interface RoomType {
  id: number;
  name: string;
  description: string;
  capacity: number;
  price: string;
  available: number;
  total: number;
  amenities: string[];
  size: string;
  images: string[];
}

const initialRoomTypes: RoomType[] = [
  {
    id: 1,
    name: "Standard Room",
    description:
      "Comfortable room with essential amenities for budget travelers",
    capacity: 2,
    price: "₹2,500",
    available: 8,
    total: 10,
    amenities: ["WiFi", "AC", "TV"],
    size: "250 sq ft",
    images: ["/placeholder.png?height=200&width=300"],
  },
  {
    id: 2,
    name: "Deluxe Room",
    description: "Spacious room with premium amenities and city view",
    capacity: 2,
    price: "₹4,200",
    available: 6,
    total: 8,
    amenities: ["WiFi", "AC", "TV", "Minibar"],
    size: "350 sq ft",
    images: [
      "/placeholder.png?height=200&width=300",
      "/placeholder.png?height=200&width=300",
    ],
  },
  {
    id: 3,
    name: "Deluxe Suite",
    description: "Elegant suite with separate living area and river view",
    capacity: 3,
    price: "₹6,500",
    available: 4,
    total: 6,
    amenities: ["WiFi", "AC", "TV", "Minibar", "Balcony"],
    size: "500 sq ft",
    images: [
      "/placeholder.png?height=200&width=300",
      "/placeholder.png?height=200&width=300",
    ],
  },
  {
    id: 4,
    name: "Premium Suite",
    description: "Luxurious suite with private jacuzzi and panoramic views",
    capacity: 4,
    price: "₹12,000",
    available: 2,
    total: 4,
    amenities: ["WiFi", "AC", "TV", "Minibar", "Balcony", "Jacuzzi"],
    size: "750 sq ft",
    images: [
      "/placeholder.png?height=200&width=300",
      "/placeholder.png?height=200&width=300",
      "/placeholder.png?height=200&width=300",
    ],
  },
];

const allAmenities = [
  { id: "WiFi", label: "WiFi", icon: Wifi },
  { id: "AC", label: "Air Conditioning", icon: AirVent },
  { id: "TV", label: "Smart TV", icon: Tv },
  { id: "Minibar", label: "Minibar", icon: Coffee },
  { id: "Parking", label: "Parking", icon: Car },
  { id: "Restaurant", label: "Room Service", icon: UtensilsCrossed },
  { id: "Gym", label: "Gym Access", icon: Dumbbell },
  { id: "Jacuzzi", label: "Jacuzzi", icon: Bath },
  { id: "Balcony", label: "Balcony", icon: BedDouble },
];

const amenityIcons: Record<string, React.ElementType> = {
  WiFi: Wifi,
  AC: AirVent,
  TV: Tv,
  Minibar: Coffee,
  Parking: Car,
  Restaurant: UtensilsCrossed,
  Gym: Dumbbell,
  Jacuzzi: Bath,
  Balcony: BedDouble,
};

interface RoomFormData {
  name: string;
  description: string;
  capacity: string;
  price: string;
  size: string;
  totalRooms: string;
  amenities: string[];
  images: string[];
}

function RoomFormDialog({
  isOpen,
  onClose,
  onSubmit,
  title,
  submitLabel,
  formData,
  setFormData,
  onToggleAmenity,
  onAddImage,
  onRemoveImage,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: () => void;
  title: string;
  submitLabel: string;
  formData: RoomFormData;
  setFormData: React.Dispatch<React.SetStateAction<RoomFormData>>;
  onToggleAmenity: (amenityId: string) => void;
  onAddImage: () => void;
  onRemoveImage: (index: number) => void;
}) {
  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <div className="space-y-6 pt-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="roomName">Room Name</Label>
              <Input
                id="roomName"
                placeholder="e.g., Executive Suite"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="size">Room Size</Label>
              <Input
                id="size"
                placeholder="350 sq ft"
                value={formData.size}
                onChange={(e) =>
                  setFormData({ ...formData, size: e.target.value })
                }
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="roomDesc">Description</Label>
            <Textarea
              id="roomDesc"
              placeholder="Describe the room..."
              rows={3}
              value={formData.description}
              onChange={(e) =>
                setFormData({ ...formData, description: e.target.value })
              }
            />
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label htmlFor="capacity">Max Guests</Label>
              <Input
                id="capacity"
                type="number"
                placeholder="2"
                value={formData.capacity}
                onChange={(e) =>
                  setFormData({ ...formData, capacity: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="price">Price per Night (₹)</Label>
              <Input
                id="price"
                type="number"
                placeholder="5000"
                value={formData.price}
                onChange={(e) =>
                  setFormData({ ...formData, price: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="totalRooms">Total Rooms</Label>
              <Input
                id="totalRooms"
                type="number"
                placeholder="10"
                value={formData.totalRooms}
                onChange={(e) =>
                  setFormData({ ...formData, totalRooms: e.target.value })
                }
              />
            </div>
          </div>

          {/* Room Photos Section */}
          <div className="space-y-3">
            <Label className="flex items-center gap-2">
              <ImageIcon className="h-4 w-4" />
              Room Photos
            </Label>
            <div className="grid grid-cols-3 gap-3">
              {formData.images.map((image, index) => (
                <div
                  key={index}
                  className="relative group aspect-video rounded-lg overflow-hidden border"
                >
                  <img
                    src={image || "/placeholder.png"}
                    alt={`Room ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                  <button
                    type="button"
                    onClick={() => onRemoveImage(index)}
                    className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
              ))}
              <button
                type="button"
                onClick={onAddImage}
                className="aspect-video rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-slate-400 hover:bg-muted/50 transition-colors flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground"
              >
                <Upload className="h-6 w-6" />
                <span className="text-xs font-medium">Add Photo</span>
              </button>
            </div>
            <p className="text-xs text-muted-foreground">
              Upload high-quality photos of the room (recommended: 3-5 images)
            </p>
          </div>

          {/* Amenities Section */}
          <div className="space-y-3">
            <Label>Room Amenities</Label>
            <div className="grid grid-cols-3 gap-3">
              {allAmenities.map((amenity) => {
                const Icon = amenity.icon;
                const isSelected = formData.amenities.includes(amenity.id);
                return (
                  <div
                    key={amenity.id}
                    className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                      isSelected
                        ? "border-slate-900 bg-slate-50 dark:border-white dark:bg-slate-800"
                        : "border-border hover:border-slate-400"
                    }`}
                    onClick={() => onToggleAmenity(amenity.id)}
                  >
                    <Checkbox checked={isSelected} />
                    <Icon className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm">{amenity.label}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <DialogFooter className="mt-6">
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button
            onClick={onSubmit}
            className="bg-slate-900 hover:bg-slate-800 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100"
          >
            {submitLabel}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export function RoomSettingsForm() {
  const [rooms, setRooms] = useState<RoomType[]>(initialRoomTypes);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedRoom, setSelectedRoom] = useState<RoomType | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    capacity: "",
    price: "",
    size: "",
    totalRooms: "",
    amenities: [] as string[],
    images: [] as string[],
  });

  const resetForm = () => {
    setFormData({
      name: "",
      description: "",
      capacity: "",
      price: "",
      size: "",
      totalRooms: "",
      amenities: [],
      images: [],
    });
  };

  const openAddDialog = () => {
    resetForm();
    setIsAddDialogOpen(true);
  };

  const openEditDialog = (room: RoomType) => {
    setSelectedRoom(room);
    setFormData({
      name: room.name,
      description: room.description,
      capacity: room.capacity.toString(),
      price: room.price.replace("₹", "").replace(",", ""),
      size: room.size,
      totalRooms: room.total.toString(),
      amenities: room.amenities,
      images: room.images,
    });
    setIsEditDialogOpen(true);
  };

  const openDeleteDialog = (room: RoomType) => {
    setSelectedRoom(room);
    setIsDeleteDialogOpen(true);
  };

  const handleAddRoom = () => {
    const newRoom: RoomType = {
      id: Math.max(...rooms.map((r) => r.id)) + 1,
      name: formData.name,
      description: formData.description,
      capacity: Number.parseInt(formData.capacity) || 2,
      price: `₹${Number.parseInt(formData.price).toLocaleString("en-IN")}`,
      available: Number.parseInt(formData.totalRooms) || 0,
      total: Number.parseInt(formData.totalRooms) || 0,
      amenities: formData.amenities,
      size: formData.size,
      images:
        formData.images.length > 0
          ? formData.images
          : ["/placeholder.png?height=200&width=300"],
    };
    setRooms([...rooms, newRoom]);
    setIsAddDialogOpen(false);
    resetForm();
  };

  const handleEditRoom = () => {
    if (!selectedRoom) return;
    setRooms(
      rooms.map((room) =>
        room.id === selectedRoom.id
          ? {
              ...room,
              name: formData.name,
              description: formData.description,
              capacity: Number.parseInt(formData.capacity) || room.capacity,
              price: `₹${Number.parseInt(formData.price).toLocaleString("en-IN")}`,
              total: Number.parseInt(formData.totalRooms) || room.total,
              amenities: formData.amenities,
              size: formData.size,
              images: formData.images,
            }
          : room
      )
    );
    setIsEditDialogOpen(false);
    setSelectedRoom(null);
    resetForm();
  };

  const handleDeleteRoom = () => {
    if (!selectedRoom) return;
    setRooms(rooms.filter((room) => room.id !== selectedRoom.id));
    setIsDeleteDialogOpen(false);
    setSelectedRoom(null);
  };

  const toggleAmenity = (amenityId: string) => {
    setFormData((prev) => ({
      ...prev,
      amenities: prev.amenities.includes(amenityId)
        ? prev.amenities.filter((a) => a !== amenityId)
        : [...prev.amenities, amenityId],
    }));
  };

  const handleAddImage = () => {
    const newImageUrl = `/placeholder.png?height=200&width=300&query=hotel room ${formData.images.length + 1}`;
    setFormData((prev) => ({
      ...prev,
      images: [...prev.images, newImageUrl],
    }));
  };

  const handleRemoveImage = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== index),
    }));
  };

  return (
    <div className="space-y-6">
      {/* Header with Add Button */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">Room Types</h2>
          <p className="text-sm text-muted-foreground">
            Manage your room categories and pricing
          </p>
        </div>
        <Button
          onClick={openAddDialog}
          className="bg-slate-900 hover:bg-slate-800 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Room Type
        </Button>
      </div>

      {/* Room Cards */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {rooms.map((room) => (
          <Card
            key={room.id}
            className="border bg-card hover:shadow-md transition-shadow overflow-hidden"
          >
            {/* Room Images Carousel */}
            {room.images.length > 0 && (
              <div className="relative h-40 overflow-hidden">
                <img
                  src={room.images[0] || "/placeholder.png"}
                  alt={room.name}
                  className="w-full h-full object-cover"
                />
                {room.images.length > 1 && (
                  <div className="absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded">
                    +{room.images.length - 1} more
                  </div>
                )}
              </div>
            )}
            <CardContent className="p-5">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="p-2.5 rounded-xl bg-slate-100 dark:bg-slate-800">
                    <BedDouble className="h-5 w-5 text-slate-600 dark:text-slate-300" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-lg">{room.name}</h3>
                    <p className="text-xs text-muted-foreground">{room.size}</p>
                  </div>
                </div>

                <div className="flex items-center gap-1">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 hover:bg-muted"
                    onClick={() => openEditDialog(room)}
                  >
                    <Edit2 className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 hover:bg-red-50 dark:hover:bg-red-950 text-red-500"
                    onClick={() => openDeleteDialog(room)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              <p className="text-sm text-muted-foreground mb-4">
                {room.description}
              </p>

              <div className="flex items-center gap-2 mb-4">
                <Badge
                  variant="outline"
                  className="bg-emerald-50 text-emerald-600 border-emerald-200 dark:bg-emerald-950 dark:text-emerald-400 dark:border-emerald-800"
                >
                  {room.available} Available
                </Badge>
                <span className="text-xs text-muted-foreground">
                  of {room.total} rooms
                </span>
              </div>

              <div className="grid grid-cols-2 gap-3 mb-4">
                <div className="p-3 rounded-lg bg-muted/30 border border-border/50">
                  <div className="flex items-center gap-2 text-muted-foreground mb-1">
                    <Users className="h-4 w-4" />
                    <span className="text-xs">Capacity</span>
                  </div>
                  <p className="font-semibold">{room.capacity} Guests</p>
                </div>
                <div className="p-3 rounded-lg bg-muted/30 border border-border/50">
                  <div className="flex items-center gap-2 text-muted-foreground mb-1">
                    <IndianRupee className="h-4 w-4" />
                    <span className="text-xs">Per Night</span>
                  </div>
                  <p className="font-semibold">{room.price}</p>
                </div>
              </div>

              <div>
                <p className="text-xs text-muted-foreground mb-2">Amenities</p>
                <div className="flex flex-wrap gap-2">
                  {room.amenities.map((amenity) => {
                    const Icon = amenityIcons[amenity] || Wifi;
                    return (
                      <Badge
                        key={amenity}
                        variant="secondary"
                        className="gap-1.5"
                      >
                        <Icon className="h-3 w-3" />
                        {amenity}
                      </Badge>
                    );
                  })}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Add Room Dialog */}
      <RoomFormDialog
        isOpen={isAddDialogOpen}
        onClose={() => setIsAddDialogOpen(false)}
        onSubmit={handleAddRoom}
        title="Add New Room Type"
        submitLabel="Add Room Type"
        formData={formData}
        setFormData={setFormData}
        onToggleAmenity={toggleAmenity}
        onAddImage={handleAddImage}
        onRemoveImage={handleRemoveImage}
      />

      {/* Edit Room Dialog */}
      <RoomFormDialog
        isOpen={isEditDialogOpen}
        onClose={() => {
          setIsEditDialogOpen(false);
          setSelectedRoom(null);
        }}
        onSubmit={handleEditRoom}
        title="Edit Room Type"
        submitLabel="Save Changes"
        formData={formData}
        setFormData={setFormData}
        onToggleAmenity={toggleAmenity}
        onAddImage={handleAddImage}
        onRemoveImage={handleRemoveImage}
      />

      {/* Delete Confirmation Dialog */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="text-red-600">Delete Room Type</DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <p className="text-muted-foreground">
              Are you sure you want to delete{" "}
              <strong>{selectedRoom?.name}</strong>? This action cannot be
              undone.
            </p>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsDeleteDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDeleteRoom}>
              <Trash2 className="h-4 w-4 mr-2" />
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
