﻿"use client";

import { Badge } from "@/components/ui/badge";

import type React from "react";

import { Suspense, useState, useRef } from "react";
import { HotelPageWrapper } from "@/roles/hotel/components/hotel-page-wrapper";
import { ProfileLoadingSkeleton } from "@/roles/hotel/components/profile/profile-loading-skeleton";
import { useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";
import {
  User,
  Shield,
  Bell,
  Camera,
  Save,
  Eye,
  EyeOff,
  Loader2,
} from "lucide-react";
import Link from "next/link";
import Image from "next/image";
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 { Switch } from "@/components/ui/switch";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";

const profileTabs = [
  { name: "Profile", param: "profile", icon: User },
  { name: "Security", param: "security", icon: Shield },
  { name: "Notifications", param: "notifications", icon: Bell },
];

interface ManageProfileClientPageProps {
  initialTab: string;
}

// Mock hotel data - in real app this would come from API/database
const initialHotelData = {
  hotelName: "Himalayan Heights Resort",
  ownerName: "Rajesh Kumar",
  email: "rajesh@himalayanheights.com",
  phone: "+91 98765 43210",
  alternatePhone: "+91 87654 32109",
  address: "Mall Road, Near Clock Tower",
  city: "Mussoorie",
  state: "Uttarakhand",
  pincode: "248179",
  gstNumber: "09AAACH7409R1ZZ",
  panNumber: "AAACH7409R",
  description:
    "A premium resort nestled in the beautiful hills of Mussoorie, offering breathtaking views of the Himalayas and world-class hospitality.",
  profileImage: "/placeholder.png?height=200&width=200",
};

export function ManageProfileClientPage({
  initialTab,
}: ManageProfileClientPageProps) {
  const searchParams = useSearchParams();
  const tab = searchParams.get("tab") || initialTab;
  const toast = useToastEnhanced();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Profile state
  const [hotelData, setHotelData] = useState(initialHotelData);
  const [isProfileSaving, setIsProfileSaving] = useState(false);
  const [profileImage, setProfileImage] = useState(
    initialHotelData.profileImage
  );

  // Security state
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isPasswordSaving, setIsPasswordSaving] = useState(false);

  // Notification state
  const [notifications, setNotifications] = useState({
    emailBookings: true,
    emailPayments: true,
    emailMarketing: false,
    smsBookings: true,
    smsPayments: true,
    pushNotifications: true,
  });

  const handleImageClick = () => {
    fileInputRef.current?.click();
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // In real app, upload to server and get URL
      const imageUrl = URL.createObjectURL(file);
      setProfileImage(imageUrl);
      toast.success({
        title: "Photo Updated",
        description: "Your profile photo has been updated successfully.",
      });
    }
  };

  const handleProfileSave = async () => {
    setIsProfileSaving(true);
    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setIsProfileSaving(false);
    toast.success({
      title: "Profile Updated",
      description: "Your profile information has been saved successfully.",
    });
  };

  const handlePasswordChange = async () => {
    if (!currentPassword || !newPassword || !confirmPassword) {
      toast.error({
        title: "Missing Fields",
        description: "Please fill in all password fields.",
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      toast.error({
        title: "Password Mismatch",
        description: "New password and confirm password do not match.",
      });
      return;
    }

    if (newPassword.length < 8) {
      toast.error({
        title: "Weak Password",
        description: "Password must be at least 8 characters long.",
      });
      return;
    }

    setIsPasswordSaving(true);
    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setIsPasswordSaving(false);
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    toast.success({
      title: "Password Changed",
      description: "Your password has been updated successfully.",
    });
  };

  const handleNotificationSave = async () => {
    toast.success({
      title: "Preferences Saved",
      description: "Your notification preferences have been updated.",
    });
  };

  return (
    <HotelPageWrapper>
      <Suspense fallback={<ProfileLoadingSkeleton />}>
        <div className="space-y-6">
          {/* Page Header */}
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-foreground">
              Manage Profile
            </h1>
            <p className="text-muted-foreground mt-1">
              Update your profile information and account settings
            </p>
          </div>

          {/* Profile Tabs */}
          <div className="flex flex-col lg:flex-row gap-6">
            {/* Sidebar */}
            <aside className="w-full lg:w-60 shrink-0">
              <div className="sticky top-24">
                <div className="bg-card border rounded-xl p-3 shadow-sm">
                  <nav
                    className="flex flex-col gap-1"
                    aria-label="Profile navigation"
                  >
                    {profileTabs.map((item) => {
                      const Icon = item.icon;
                      const active = tab === item.param;

                      return (
                        <Link
                          key={item.param}
                          href={`/hotel/manage-profile?tab=${item.param}`}
                          className={cn(
                            "flex items-center gap-3 px-3 py-2.5 rounded-lg font-medium text-sm transition-all duration-200",
                            active
                              ? "bg-slate-900 dark:bg-white text-white dark:text-slate-900 shadow-md"
                              : "text-muted-foreground hover:text-foreground hover:bg-muted"
                          )}
                        >
                          <Icon className="h-4 w-4" />
                          <span>{item.name}</span>
                        </Link>
                      );
                    })}
                  </nav>
                </div>
              </div>
            </aside>

            {/* Content */}
            <div className="flex-1 max-w-3xl">
              {/* Profile Tab */}
              {tab === "profile" && (
                <div className="space-y-6">
                  {/* Profile Photo Card */}
                  <Card>
                    <CardHeader>
                      <CardTitle>Profile Photo</CardTitle>
                      <CardDescription>
                        Update your hotel profile photo
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-6">
                        <div className="relative group">
                          <div className="h-24 w-24 rounded-full overflow-hidden border-4 border-muted">
                            <Image
                              src={profileImage || "/placeholder.png"}
                              alt="Profile"
                              width={96}
                              height={96}
                              className="h-full w-full object-cover"
                            />
                          </div>
                          <button
                            onClick={handleImageClick}
                            className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                          >
                            <Camera className="h-6 w-6 text-white" />
                          </button>
                          <input
                            ref={fileInputRef}
                            type="file"
                            accept="image/*"
                            onChange={handleImageChange}
                            className="hidden"
                          />
                        </div>
                        <div>
                          <Button variant="outline" onClick={handleImageClick}>
                            <Camera className="h-4 w-4 mr-2" />
                            Change Photo
                          </Button>
                          <p className="text-xs text-muted-foreground mt-2">
                            JPG, PNG or GIF. Max size 2MB.
                          </p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Basic Information Card */}
                  <Card>
                    <CardHeader>
                      <CardTitle>Basic Information</CardTitle>
                      <CardDescription>
                        Update your hotel and owner details
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid gap-4 sm:grid-cols-2">
                        <div className="space-y-2">
                          <Label htmlFor="hotelName">Hotel Name</Label>
                          <Input
                            id="hotelName"
                            value={hotelData.hotelName}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                hotelName: e.target.value,
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="ownerName">Owner Name</Label>
                          <Input
                            id="ownerName"
                            value={hotelData.ownerName}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                ownerName: e.target.value,
                              })
                            }
                          />
                        </div>
                      </div>
                      <div className="grid gap-4 sm:grid-cols-2">
                        <div className="space-y-2">
                          <Label htmlFor="email">Email Address</Label>
                          <Input
                            id="email"
                            type="email"
                            value={hotelData.email}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                email: e.target.value,
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="phone">Phone Number</Label>
                          <Input
                            id="phone"
                            value={hotelData.phone}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                phone: e.target.value,
                              })
                            }
                          />
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="alternatePhone">
                          Alternate Phone (Optional)
                        </Label>
                        <Input
                          id="alternatePhone"
                          value={hotelData.alternatePhone}
                          onChange={(e) =>
                            setHotelData({
                              ...hotelData,
                              alternatePhone: e.target.value,
                            })
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="description">Hotel Description</Label>
                        <Textarea
                          id="description"
                          rows={4}
                          value={hotelData.description}
                          onChange={(e) =>
                            setHotelData({
                              ...hotelData,
                              description: e.target.value,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  {/* Address Card */}
                  <Card>
                    <CardHeader>
                      <CardTitle>Address Details</CardTitle>
                      <CardDescription>
                        Update your hotel location
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="address">Street Address</Label>
                        <Input
                          id="address"
                          value={hotelData.address}
                          onChange={(e) =>
                            setHotelData({
                              ...hotelData,
                              address: e.target.value,
                            })
                          }
                        />
                      </div>
                      <div className="grid gap-4 sm:grid-cols-3">
                        <div className="space-y-2">
                          <Label htmlFor="city">City</Label>
                          <Input
                            id="city"
                            value={hotelData.city}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                city: e.target.value,
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="state">State</Label>
                          <Input
                            id="state"
                            value={hotelData.state}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                state: e.target.value,
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="pincode">Pincode</Label>
                          <Input
                            id="pincode"
                            value={hotelData.pincode}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                pincode: e.target.value,
                              })
                            }
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Business Details Card */}
                  <Card>
                    <CardHeader>
                      <CardTitle>Business Details</CardTitle>
                      <CardDescription>
                        Your tax and business registration information
                      </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"
                            value={hotelData.gstNumber}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                gstNumber: e.target.value,
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="panNumber">PAN Number</Label>
                          <Input
                            id="panNumber"
                            value={hotelData.panNumber}
                            onChange={(e) =>
                              setHotelData({
                                ...hotelData,
                                panNumber: e.target.value,
                              })
                            }
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Save Button */}
                  <div className="flex justify-end">
                    <Button
                      onClick={handleProfileSave}
                      disabled={isProfileSaving}
                    >
                      {isProfileSaving ? (
                        <>
                          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                          Saving...
                        </>
                      ) : (
                        <>
                          <Save className="h-4 w-4 mr-2" />
                          Save Changes
                        </>
                      )}
                    </Button>
                  </div>
                </div>
              )}

              {/* Security Tab */}
              {tab === "security" && (
                <div className="space-y-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>Change Password</CardTitle>
                      <CardDescription>
                        Update your account password for security
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="currentPassword">
                          Current Password
                        </Label>
                        <div className="relative">
                          <Input
                            id="currentPassword"
                            type={showCurrentPassword ? "text" : "password"}
                            value={currentPassword}
                            onChange={(e) => setCurrentPassword(e.target.value)}
                            placeholder="Enter current password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() =>
                              setShowCurrentPassword(!showCurrentPassword)
                            }
                          >
                            {showCurrentPassword ? (
                              <EyeOff className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <Eye className="h-4 w-4 text-muted-foreground" />
                            )}
                          </Button>
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="newPassword">New Password</Label>
                        <div className="relative">
                          <Input
                            id="newPassword"
                            type={showNewPassword ? "text" : "password"}
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            placeholder="Enter new password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() => setShowNewPassword(!showNewPassword)}
                          >
                            {showNewPassword ? (
                              <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">
                          Password must be at least 8 characters long
                        </p>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="confirmPassword">
                          Confirm New Password
                        </Label>
                        <div className="relative">
                          <Input
                            id="confirmPassword"
                            type={showConfirmPassword ? "text" : "password"}
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            placeholder="Confirm new password"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() =>
                              setShowConfirmPassword(!showConfirmPassword)
                            }
                          >
                            {showConfirmPassword ? (
                              <EyeOff className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <Eye className="h-4 w-4 text-muted-foreground" />
                            )}
                          </Button>
                        </div>
                      </div>
                      <div className="flex justify-end pt-4">
                        <Button
                          onClick={handlePasswordChange}
                          disabled={isPasswordSaving}
                        >
                          {isPasswordSaving ? (
                            <>
                              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                              Updating...
                            </>
                          ) : (
                            <>
                              <Shield className="h-4 w-4 mr-2" />
                              Update Password
                            </>
                          )}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Two-Factor Authentication</CardTitle>
                      <CardDescription>
                        Add an extra layer of security to your account
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Enable 2FA</p>
                          <p className="text-sm text-muted-foreground">
                            Secure your account with two-factor authentication
                          </p>
                        </div>
                        <Switch />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Login Sessions</CardTitle>
                      <CardDescription>
                        Manage your active login sessions
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                          <div>
                            <p className="font-medium text-sm">
                              Current Session
                            </p>
                            <p className="text-xs text-muted-foreground">
                              Chrome on Windows - Active now
                            </p>
                          </div>
                          <Badge variant="secondary">Current</Badge>
                        </div>
                        <Button
                          variant="outline"
                          className="w-full bg-transparent"
                        >
                          Sign out of all other sessions
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              )}

              {/* Notifications Tab */}
              {tab === "notifications" && (
                <div className="space-y-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>Email Notifications</CardTitle>
                      <CardDescription>
                        Configure your email notification preferences
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Booking Notifications</p>
                          <p className="text-sm text-muted-foreground">
                            Receive emails for new bookings and cancellations
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailBookings}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailBookings: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Payment Notifications</p>
                          <p className="text-sm text-muted-foreground">
                            Receive emails for payment updates and withdrawals
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailPayments}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailPayments: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Marketing Emails</p>
                          <p className="text-sm text-muted-foreground">
                            Receive promotional emails and platform updates
                          </p>
                        </div>
                        <Switch
                          checked={notifications.emailMarketing}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              emailMarketing: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>SMS Notifications</CardTitle>
                      <CardDescription>
                        Configure your SMS notification preferences
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Booking SMS</p>
                          <p className="text-sm text-muted-foreground">
                            Receive SMS for new bookings
                          </p>
                        </div>
                        <Switch
                          checked={notifications.smsBookings}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              smsBookings: checked,
                            })
                          }
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">Payment SMS</p>
                          <p className="text-sm text-muted-foreground">
                            Receive SMS for payment confirmations
                          </p>
                        </div>
                        <Switch
                          checked={notifications.smsPayments}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              smsPayments: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Push Notifications</CardTitle>
                      <CardDescription>
                        Configure browser push notifications
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium">
                            Enable Push Notifications
                          </p>
                          <p className="text-sm text-muted-foreground">
                            Receive instant notifications in your browser
                          </p>
                        </div>
                        <Switch
                          checked={notifications.pushNotifications}
                          onCheckedChange={(checked) =>
                            setNotifications({
                              ...notifications,
                              pushNotifications: checked,
                            })
                          }
                        />
                      </div>
                    </CardContent>
                  </Card>

                  <div className="flex justify-end">
                    <Button onClick={handleNotificationSave}>
                      <Save className="h-4 w-4 mr-2" />
                      Save Preferences
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </Suspense>
    </HotelPageWrapper>
  );
}

export default ManageProfileClientPage;
