'use client'

import { useEffect, useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Skeleton } from '@/components/ui/skeleton'
import { ExternalLink, Hotel as HotelIcon, Loader2, Save } from 'lucide-react'

interface Props {
  programId: string
}

export function HotelsTab({ programId }: Props) {
  const utils = trpc.useUtils()
  const { data: hotel, isLoading } = trpc.logistics.getHotel.useQuery({ programId })

  const [name, setName] = useState('')
  const [address, setAddress] = useState('')
  const [link, setLink] = useState('')
  const [notes, setNotes] = useState('')

  // Sync form state from server data on first load / after save.
  useEffect(() => {
    if (hotel) {
      setName(hotel.name)
      setAddress(hotel.address ?? '')
      setLink(hotel.link ?? '')
      setNotes(hotel.notes ?? '')
    }
  }, [hotel])

  const upsertMutation = trpc.logistics.upsertHotel.useMutation({
    onSuccess: () => {
      toast.success('Hotel saved')
      utils.logistics.getHotel.invalidate({ programId })
    },
    onError: (err) => toast.error(err.message),
  })

  const handleSave = () => {
    if (!name.trim()) {
      toast.error('Hotel name is required')
      return
    }
    upsertMutation.mutate({
      programId,
      name: name.trim(),
      address: address.trim() || undefined,
      link: link.trim() || '',
      notes: notes.trim() || undefined,
    })
  }

  if (isLoading) return <Skeleton className="h-96 w-full" />

  const dirty =
    name !== (hotel?.name ?? '') ||
    address !== (hotel?.address ?? '') ||
    link !== (hotel?.link ?? '') ||
    notes !== (hotel?.notes ?? '')

  return (
    <div className="grid gap-4 md:grid-cols-3">
      <div className="md:col-span-2">
        <Card>
          <CardHeader>
            <div className="flex items-center gap-2">
              <HotelIcon className="text-muted-foreground h-4 w-4" />
              <CardTitle className="text-base">Hotel for this edition</CardTitle>
            </div>
            <CardDescription>
              One hotel per edition. Used in confirmation emails and finalist communications.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="hotel-name">Name *</Label>
              <Input
                id="hotel-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Hôtel de Paris"
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="hotel-address">Address</Label>
              <Textarea
                id="hotel-address"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                placeholder="Place du Casino, 98000 Monaco"
                rows={2}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="hotel-link">Hotel website / booking link</Label>
              <Input
                id="hotel-link"
                type="url"
                value={link}
                onChange={(e) => setLink(e.target.value)}
                placeholder="https://hoteldeparismontecarlo.com"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="hotel-notes">Internal notes</Label>
              <Textarea
                id="hotel-notes"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Check-in time, special arrangements, etc."
                rows={3}
              />
            </div>
            <div className="flex justify-end">
              <Button
                onClick={handleSave}
                disabled={!dirty || upsertMutation.isPending}
              >
                {upsertMutation.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Save className="mr-2 h-4 w-4" />
                )}
                Save
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="md:col-span-1">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Email preview</CardTitle>
            <CardDescription>What teams will see in confirmation emails.</CardDescription>
          </CardHeader>
          <CardContent>
            {!name.trim() ? (
              <p className="text-muted-foreground text-sm">Save a hotel to see the preview.</p>
            ) : (
              <div className="bg-muted/30 rounded-md border p-4 text-sm">
                <div className="text-muted-foreground mb-1 text-xs uppercase tracking-wide">
                  Your accommodation
                </div>
                <div className="font-semibold">{name}</div>
                {address.trim() && (
                  <div className="text-muted-foreground mt-1 whitespace-pre-line text-xs">
                    {address}
                  </div>
                )}
                {link.trim() && (
                  <a
                    href={link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
                  >
                    Visit hotel website <ExternalLink className="h-3 w-3" />
                  </a>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
