"use client"

import type React from "react"

import { useEffect, useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { AgentHeader } from "@/components/agent/agent-header"
import { getClientSession, validateSessionData } from "@/lib/auth/client-session"
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 { Building2, Upload, X, Save, Phone, MapPin, ImageIcon } from "lucide-react"
import Image from "next/image"

export default function ItinerarySettingPage() {
  const router = useRouter()
  const [agentEmail, setAgentEmail] = useState<string>("agent@teertham.com")
  const [agentName, setAgentName] = useState<string>("Agent")
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [businessInfo, setBusinessInfo] = useState({
    businessName: "",
    businessLogo: null as string | null,
    businessAddress: "",
    businessPhone: "",
    alternatePhone: "",
  })

  useEffect(() => {
    const session = getClientSession("agent_session")
    if (!session || !validateSessionData(session) || session.role !== "agent") {
      router.push("/login")
      return
    }
    setAgentEmail(session.email || "agent@teertham.com")
    setAgentName(session.name || "Agent")
    setIsLoading(false)
  }, [router])

  const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onloadend = () => {
        setBusinessInfo({ ...businessInfo, businessLogo: reader.result as string })
      }
      reader.readAsDataURL(file)
    }
  }

  const handleRemoveLogo = () => {
    setBusinessInfo({ ...businessInfo, businessLogo: null })
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  const handleSave = async () => {
    setIsSaving(true)
    // Simulate save
    await new Promise((resolve) => setTimeout(resolve, 1000))
    setIsSaving(false)
  }

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-500" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      <AgentHeader agentEmail={agentEmail} agentName={agentName} />
      <main className="container mx-auto p-4 md:p-6 lg:p-8 max-w-3xl">
        <div className="mb-8">
          <h1 className="text-2xl font-bold">Itinerary Setting</h1>
          <p className="text-muted-foreground">Configure your business details that will appear on itineraries</p>
        </div>

        <Card className="border-border/50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="h-5 w-5 text-teal-600" />
              Business Information
            </CardTitle>
            <CardDescription>
              This information will be displayed on all itineraries generated for your clients
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <Label>Business Logo</Label>
              <div className="flex items-start gap-4">
                <div className="relative w-32 h-32 rounded-xl border-2 border-dashed border-border/50 flex items-center justify-center bg-muted/30 overflow-hidden">
                  {businessInfo.businessLogo ? (
                    <>
                      <Image
                        src={businessInfo.businessLogo || "/placeholder.svg"}
                        alt="Business Logo"
                        fill
                        className="object-contain p-2"
                      />
                      <button
                        onClick={handleRemoveLogo}
                        className="absolute top-1 right-1 p-1 rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90 transition-colors"
                      >
                        <X className="h-4 w-4" />
                      </button>
                    </>
                  ) : (
                    <div className="text-center">
                      <ImageIcon className="h-8 w-8 text-muted-foreground mx-auto mb-1" />
                      <span className="text-xs text-muted-foreground">No logo</span>
                    </div>
                  )}
                </div>
                <div className="flex-1">
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleLogoUpload}
                    className="hidden"
                    id="logo-upload"
                  />
                  <Button variant="outline" onClick={() => fileInputRef.current?.click()} className="mb-2">
                    <Upload className="h-4 w-4 mr-2" />
                    Upload Logo
                  </Button>
                  <p className="text-xs text-muted-foreground">
                    Recommended: Square image, at least 200x200px. PNG or JPG format.
                  </p>
                </div>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="businessName">Business Name</Label>
              <div className="relative">
                <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="businessName"
                  value={businessInfo.businessName}
                  onChange={(e) => setBusinessInfo({ ...businessInfo, businessName: e.target.value })}
                  placeholder="Enter your business name"
                  className="pl-10"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="businessAddress">Business Address</Label>
              <div className="relative">
                <MapPin className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Textarea
                  id="businessAddress"
                  value={businessInfo.businessAddress}
                  onChange={(e) => setBusinessInfo({ ...businessInfo, businessAddress: e.target.value })}
                  placeholder="Enter your complete business address"
                  className="pl-10 min-h-[100px] resize-none"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="businessPhone">Business Phone Number</Label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="businessPhone"
                    type="tel"
                    value={businessInfo.businessPhone}
                    onChange={(e) => setBusinessInfo({ ...businessInfo, businessPhone: e.target.value })}
                    placeholder="+91 XXXXX XXXXX"
                    className="pl-10"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="alternatePhone">Alternate Phone Number</Label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="alternatePhone"
                    type="tel"
                    value={businessInfo.alternatePhone}
                    onChange={(e) => setBusinessInfo({ ...businessInfo, alternatePhone: e.target.value })}
                    placeholder="+91 XXXXX XXXXX"
                    className="pl-10"
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-end pt-4 border-t border-border/50">
              <Button onClick={handleSave} disabled={isSaving} className="frontend-btn">
                {isSaving ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                    Saving...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    Save Settings
                  </>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  )
}
