"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Save, Building2, User, MapPin, FileText, Calendar, Lock, Eye, EyeOff } from "lucide-react"
import {
  hotelPartnerSchema,
  createHotelPartnerSchema,
  type CreateHotelPartnerInput,
} from "@/lib/validations/hotel-partner"
import { hotelPartnerDataStore } from "@/lib/data/hotel-partners"
import { locationDataStore, type State, type City } from "@/lib/data/locations"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"

interface HotelPartnerFormProps {
  partnerId?: string
}

export function HotelPartnerForm({ partnerId }: HotelPartnerFormProps) {
  const router = useRouter()
  const toast = useToastEnhanced()
  const isEditing = Boolean(partnerId)

  const [states, setStates] = useState<State[]>([])
  const [cities, setCities] = useState<City[]>([])
  const [selectedStateId, setSelectedStateId] = useState<string>("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [currentPassword, setCurrentPassword] = useState<string>("")

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<CreateHotelPartnerInput>({
    resolver: zodResolver(isEditing ? hotelPartnerSchema : createHotelPartnerSchema),
    defaultValues: {
      hotelName: "",
      ownerName: "",
      stateId: "",
      cityId: "",
      email: "",
      phone: "",
      password: "",
      address: "",
      gstNumber: "",
      panNumber: "",
      registrationNumber: "",
      licenseNumber: "",
      otherDocuments: "",
      since: "",
    },
  })

  const watchedStateId = watch("stateId")

  // Load states on mount
  useEffect(() => {
    const activeStates = locationDataStore.getActiveStates()
    setStates(activeStates)
  }, [])

  // Load cities when state changes
  useEffect(() => {
    if (watchedStateId) {
      const stateCities = locationDataStore.getCitiesByState(watchedStateId).filter((c) => c.status === "active")
      setCities(stateCities)
      setSelectedStateId(watchedStateId)
    } else {
      setCities([])
    }
  }, [watchedStateId])

  // Load partner data if editing
  useEffect(() => {
    if (partnerId) {
      const partner = hotelPartnerDataStore.getPartnerById(partnerId)
      if (partner) {
        reset({
          hotelName: partner.hotelName,
          ownerName: partner.ownerName,
          stateId: partner.stateId,
          cityId: partner.cityId,
          email: partner.email,
          phone: partner.phone,
          password: "",
          address: partner.address,
          gstNumber: partner.documents.gstNumber,
          panNumber: partner.documents.panNumber,
          registrationNumber: partner.documents.registrationNumber,
          licenseNumber: partner.documents.licenseNumber,
          otherDocuments: partner.documents.otherDocuments.join(", "),
          since: partner.since,
        })
        setSelectedStateId(partner.stateId)
        setCurrentPassword(partner.password)
      }
    }
  }, [partnerId, reset])

  const onSubmit = async (data: CreateHotelPartnerInput) => {
    setIsSubmitting(true)

    // Simulate network delay
    await new Promise((resolve) => setTimeout(resolve, 500))

    const partnerData = {
      hotelName: data.hotelName,
      ownerName: data.ownerName,
      stateId: data.stateId,
      cityId: data.cityId,
      email: data.email,
      phone: data.phone,
      password: data.password || "",
      address: data.address,
      documents: {
        gstNumber: data.gstNumber,
        panNumber: data.panNumber,
        registrationNumber: data.registrationNumber,
        licenseNumber: data.licenseNumber,
        otherDocuments: data.otherDocuments
          ? data.otherDocuments
              .split(",")
              .map((d) => d.trim())
              .filter(Boolean)
          : [],
      },
      since: data.since,
    }

    if (isEditing && partnerId) {
      const updated = hotelPartnerDataStore.updatePartner(partnerId, partnerData)
      if (updated) {
        toast.success({
          title: "Partner Updated",
          description: `${data.hotelName} has been updated successfully.`,
        })
        router.push("/admin/hotel-partners")
      } else {
        toast.error({
          title: "Update Failed",
          description: "Email already exists or invalid data provided.",
        })
      }
    } else {
      const created = hotelPartnerDataStore.addPartner(partnerData)
      if (created) {
        toast.success({
          title: "Partner Added",
          description: `${data.hotelName} has been added successfully.`,
        })
        router.push("/admin/hotel-partners")
      } else {
        toast.error({
          title: "Creation Failed",
          description: "Email already exists or invalid data provided.",
        })
      }
    }

    setIsSubmitting(false)
  }

  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 Hotel Partner" : "Add New Hotel Partner"}
          </h1>
          <p className="text-muted-foreground">
            {isEditing ? "Update hotel partner information" : "Register a new hotel partner on the platform"}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Basic Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="h-5 w-5 text-primary" aria-hidden="true" />
              Hotel Information
            </CardTitle>
            <CardDescription>Basic details about the hotel</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="hotelName">Hotel Name *</Label>
              <Input
                id="hotelName"
                placeholder="Enter hotel name"
                {...register("hotelName")}
                aria-invalid={!!errors.hotelName}
              />
              {errors.hotelName && <p className="text-sm text-destructive">{errors.hotelName.message}</p>}
            </div>
            <div className="space-y-2">
              <Label htmlFor="ownerName">Owner Name *</Label>
              <Input
                id="ownerName"
                placeholder="Enter owner name"
                {...register("ownerName")}
                aria-invalid={!!errors.ownerName}
              />
              {errors.ownerName && <p className="text-sm text-destructive">{errors.ownerName.message}</p>}
            </div>
          </CardContent>
        </Card>

        {/* Contact Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5 text-primary" aria-hidden="true" />
              Contact Information
            </CardTitle>
            <CardDescription>Contact details for the hotel partner</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="email">Email Address *</Label>
              <Input
                id="email"
                type="email"
                placeholder="hotel@example.com"
                {...register("email")}
                aria-invalid={!!errors.email}
              />
              {errors.email && <p className="text-sm text-destructive">{errors.email.message}</p>}
            </div>
            <div className="space-y-2">
              <Label htmlFor="phone">Phone Number *</Label>
              <Input
                id="phone"
                type="tel"
                placeholder="+91 9876543210"
                {...register("phone")}
                aria-invalid={!!errors.phone}
              />
              {errors.phone && <p className="text-sm text-destructive">{errors.phone.message}</p>}
            </div>
          </CardContent>
        </Card>

        {/* Login Credentials - Show for both add and edit */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Lock className="h-5 w-5 text-primary" aria-hidden="true" />
              Login Credentials
            </CardTitle>
            <CardDescription>
              {isEditing ? "View current password or set a new one" : "Set password for hotel partner login"}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {isEditing && currentPassword && (
              <div className="space-y-2 max-w-md">
                <Label>Current Password</Label>
                <div className="relative">
                  <Input
                    type={showCurrentPassword ? "text" : "password"}
                    value={currentPassword}
                    readOnly
                    className="pr-10 bg-muted"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                    onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                    aria-label={showCurrentPassword ? "Hide current password" : "Show current password"}
                  >
                    {showCurrentPassword ? (
                      <EyeOff className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <Eye className="h-4 w-4 text-muted-foreground" />
                    )}
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">This is the current password for this hotel partner</p>
              </div>
            )}

            <div className="space-y-2 max-w-md">
              <Label htmlFor="password">
                {isEditing ? "New Password (leave blank to keep current)" : "Password *"}
              </Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder={isEditing ? "Enter new password (optional)" : "Enter secure password"}
                  {...register("password")}
                  aria-invalid={!!errors.password}
                  className="pr-10"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                  onClick={() => setShowPassword(!showPassword)}
                  aria-label={showPassword ? "Hide password" : "Show password"}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4 text-muted-foreground" />
                  ) : (
                    <Eye className="h-4 w-4 text-muted-foreground" />
                  )}
                </Button>
              </div>
              {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}
              <p className="text-xs text-muted-foreground">
                {isEditing
                  ? "Leave blank to keep the current password, or enter a new one (8+ chars with uppercase, lowercase, number)"
                  : "Must be at least 8 characters with uppercase, lowercase, and number"}
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Location */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5 text-primary" aria-hidden="true" />
              Location Details
            </CardTitle>
            <CardDescription>Hotel location information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="stateId">State *</Label>
                <Select
                  value={watchedStateId}
                  onValueChange={(value) => {
                    setValue("stateId", value)
                    setValue("cityId", "")
                  }}
                >
                  <SelectTrigger id="stateId" aria-invalid={!!errors.stateId}>
                    <SelectValue placeholder="Select state" />
                  </SelectTrigger>
                  <SelectContent>
                    {states.map((state) => (
                      <SelectItem key={state.id} value={state.id}>
                        {state.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {errors.stateId && <p className="text-sm text-destructive">{errors.stateId.message}</p>}
              </div>
              <div className="space-y-2">
                <Label htmlFor="cityId">City *</Label>
                <Select
                  value={watch("cityId")}
                  onValueChange={(value) => setValue("cityId", value)}
                  disabled={!selectedStateId}
                >
                  <SelectTrigger id="cityId" aria-invalid={!!errors.cityId}>
                    <SelectValue placeholder={selectedStateId ? "Select city" : "Select state first"} />
                  </SelectTrigger>
                  <SelectContent>
                    {cities.map((city) => (
                      <SelectItem key={city.id} value={city.id}>
                        {city.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {errors.cityId && <p className="text-sm text-destructive">{errors.cityId.message}</p>}
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="address">Full Address *</Label>
              <Textarea
                id="address"
                placeholder="Enter complete address with landmark"
                rows={3}
                {...register("address")}
                aria-invalid={!!errors.address}
              />
              {errors.address && <p className="text-sm text-destructive">{errors.address.message}</p>}
            </div>
          </CardContent>
        </Card>

        {/* Documents */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-primary" aria-hidden="true" />
              Documents & Certifications
            </CardTitle>
            <CardDescription>Legal and registration documents</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="gstNumber">GST Number *</Label>
                <Input
                  id="gstNumber"
                  placeholder="22AAAAA0000A1Z5"
                  className="uppercase"
                  {...register("gstNumber")}
                  aria-invalid={!!errors.gstNumber}
                />
                {errors.gstNumber && <p className="text-sm text-destructive">{errors.gstNumber.message}</p>}
              </div>
              <div className="space-y-2">
                <Label htmlFor="panNumber">PAN Number *</Label>
                <Input
                  id="panNumber"
                  placeholder="AAAAA0000A"
                  className="uppercase"
                  {...register("panNumber")}
                  aria-invalid={!!errors.panNumber}
                />
                {errors.panNumber && <p className="text-sm text-destructive">{errors.panNumber.message}</p>}
              </div>
            </div>

            <Separator />

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="registrationNumber">Registration Number *</Label>
                <Input
                  id="registrationNumber"
                  placeholder="HOTEL/2024/12345"
                  {...register("registrationNumber")}
                  aria-invalid={!!errors.registrationNumber}
                />
                {errors.registrationNumber && (
                  <p className="text-sm text-destructive">{errors.registrationNumber.message}</p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="licenseNumber">License Number *</Label>
                <Input
                  id="licenseNumber"
                  placeholder="LIC/CITY/2024/001"
                  {...register("licenseNumber")}
                  aria-invalid={!!errors.licenseNumber}
                />
                {errors.licenseNumber && <p className="text-sm text-destructive">{errors.licenseNumber.message}</p>}
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="otherDocuments">Other Documents (comma separated)</Label>
              <Input
                id="otherDocuments"
                placeholder="Fire Safety Certificate, Health License, Tourism License"
                {...register("otherDocuments")}
              />
              <p className="text-xs text-muted-foreground">Enter additional certifications separated by commas</p>
            </div>
          </CardContent>
        </Card>

        {/* Partner Since */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5 text-primary" aria-hidden="true" />
              Partnership Details
            </CardTitle>
            <CardDescription>When did this hotel join as a partner?</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-w-xs">
              <Label htmlFor="since">Partner Since *</Label>
              <Input id="since" type="date" {...register("since")} aria-invalid={!!errors.since} />
              {errors.since && <p className="text-sm text-destructive">{errors.since.message}</p>}
            </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 type="submit" disabled={isSubmitting}>
            <Save className="mr-2 h-4 w-4" aria-hidden="true" />
            {isSubmitting ? "Saving..." : isEditing ? "Update Partner" : "Add Partner"}
          </Button>
        </div>
      </form>
    </div>
  )
}
