"use client"

import { useState } from "react";
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import {
    Save,
    Eye,
    Globe,
    Phone,
    Mail,
    MapPin,
    Clock,
    Scissors,
    Plus,
    X,
    ExternalLink,
    CheckCircle2,
    Camera,
    Upload,
    Trash2
} from "lucide-react";
import { useToaster } from "@/context/ToasterContext";

interface ServiceItem {
    id: string;
    name: string;
    duration: string;
    price: string;
}

interface WorkPhoto {
    id: string;
    url: string;
    caption: string;
}

export function MyWebsite() {
    const [subdomain, setSubdomain] = useState("hairraizers91");
    const [isSubdomainAvailable, setIsSubdomainAvailable] = useState(true);
    const { showSuccess } = useToaster();

    // Business info state
    const [businessName, setBusinessName] = useState("Hair Raizers 91");
    const [tagline, setTagline] = useState("Premium Hair Styling & Beauty Services");
    const [description, setDescription] = useState("Welcome to Hair Raizers 91, where style meets sophistication. Our expert stylists are dedicated to bringing out your best look with personalized services and premium products.");

    // Contact info
    const [phone, setPhone] = useState("+91 98765 43210");
    const [email, setEmail] = useState("hello@hairraizers91.com");
    const [address, setAddress] = useState("123 Fashion Street, Mumbai, Maharashtra 400001");
    const [hours, setHours] = useState("Mon-Sat: 10:00 - 20:00");

    // Services
    const [services, setServices] = useState<ServiceItem[]>([
        { id: "1", name: "Haircut & Styling", duration: "45 min", price: "₹500" },
        { id: "2", name: "Hair Color", duration: "2 hrs", price: "₹2,500" },
        { id: "3", name: "Hair Spa Treatment", duration: "1.5 hrs", price: "₹1,500" },
        { id: "4", name: "Beard Grooming", duration: "30 min", price: "₹300" },
    ]);

    // Work photos
    const [workPhotos, setWorkPhotos] = useState<WorkPhoto[]>([
        { id: "1", url: "https://images.unsplash.com/photo-1560066984-138dadb4c035?w=300&h=300&fit=crop", caption: "Balayage highlights" },
        { id: "2", url: "https://images.unsplash.com/photo-1522337360788-8b13dee7a37e?w=300&h=300&fit=crop", caption: "Men's fade haircut" },
        { id: "3", url: "https://images.unsplash.com/photo-1595476108010-b4d1f102b1b1?w=300&h=300&fit=crop", caption: "Bridal styling" },
    ]);

    const handleSubdomainChange = (value: string) => {
        const sanitized = value.toLowerCase().replace(/[^a-z0-9-]/g, '');
        setSubdomain(sanitized);
        // Simulate availability check
        setIsSubdomainAvailable(sanitized.length >= 3);
    };

    const addService = () => {
        const newService: ServiceItem = {
            id: Date.now().toString(),
            name: "New Service",
            duration: "30 min",
            price: "₹0",
        };
        setServices([...services, newService]);
    };

    const removeService = (id: string) => {
        setServices(services.filter(s => s.id !== id));
    };

    const updateService = (id: string, field: keyof ServiceItem, value: string) => {
        setServices(services.map(s => s.id === id ? { ...s, [field]: value } : s));
    };

    const addPhoto = () => {
        const newPhoto: WorkPhoto = {
            id: Date.now().toString(),
            url: "https://images.unsplash.com/photo-1562322140-8baeececf3df?w=300&h=300&fit=crop",
            caption: "New photo",
        };
        setWorkPhotos([...workPhotos, newPhoto]);
    };

    const removePhoto = (id: string) => {
        setWorkPhotos(workPhotos.filter(p => p.id !== id));
    };

    const updatePhotoCaption = (id: string, caption: string) => {
        setWorkPhotos(workPhotos.map(p => p.id === id ? { ...p, caption } : p));
    };

    const handleSave = () => {
        showSuccess("Your landing page has been updated successfully.");
    };

    const handlePublish = () => {
        showSuccess(`Your website is now live at ${subdomain}.readyreception.com`);
    };

    return (
        <div className="space-y-6 animate-fade-in">
            {/* Header */}
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 -mt-2">
                <div>
                    <p className="text-muted-foreground">
                        Create and customize your business landing page
                    </p>
                </div>
                <div className="flex gap-3">
                    <Button variant="outline" className="gap-2" onClick={() => window.open(`https://${subdomain}.readyreception.com`, '_blank')}>
                        <ExternalLink className="w-4 h-4" />
                        View Live
                    </Button>
                    <Button className="gap-2 bg-primary-gradient text-white" onClick={handlePublish}>
                        <Globe className="w-4 h-4" />
                        Publish
                    </Button>
                </div>
            </div>

            {/* Subdomain Setup */}
            <Card className="shadow-card border-stat-blue/20 bg-stat-blue-bg/30">
                <CardContent className="pt-6">
                    <div className="flex flex-col md:flex-row md:items-end gap-4">
                        <div className="flex-1 space-y-2">
                            <Label htmlFor="subdomain" className="text-base font-medium">Your Website URL</Label>
                            <div className="flex items-center">
                                <span className="text-muted-foreground text-sm bg-muted px-3 py-2 rounded-l-md border border-r-0">
                                    https://
                                </span>
                                <Input
                                    id="subdomain"
                                    value={subdomain}
                                    onChange={(e) => handleSubdomainChange(e.target.value)}
                                    className="rounded-none border-x-0 text-center font-medium"
                                    placeholder="yourname"
                                />
                                <span className="text-muted-foreground text-sm bg-muted px-3 py-2 rounded-r-md border border-l-0">
                                    .readyreception.com
                                </span>
                            </div>
                        </div>
                        {subdomain && (
                            <Badge
                                variant={isSubdomainAvailable ? "default" : "destructive"}
                                className={`gap-1 h-8 ${isSubdomainAvailable ? 'bg-stat-emerald' : ''}`}
                            >
                                {isSubdomainAvailable ? (
                                    <>
                                        <CheckCircle2 className="w-3 h-3" />
                                        Available
                                    </>
                                ) : (
                                    "Too short"
                                )}
                            </Badge>
                        )}
                    </div>
                </CardContent>
            </Card>

            <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
                {/* Editor Panel */}
                <div className="space-y-6">
                    <Tabs defaultValue="info" className="w-full">
                        <TabsList className="grid w-full grid-cols-4 bg-white border border-gray-100 rounded-xl h-12 p-1 gap-1 shadow-sm">
                            <TabsTrigger
                                value="info"
                                className="rounded-lg font-bold transition-all duration-200 text-stat-blue data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-md border-none"
                            >
                                Business Info
                            </TabsTrigger>
                            <TabsTrigger
                                value="services"
                                className="rounded-lg font-bold transition-all duration-200 text-stat-blue data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-md border-none"
                            >
                                Services
                            </TabsTrigger>
                            <TabsTrigger
                                value="mywork"
                                className="rounded-lg font-bold transition-all duration-200 text-stat-blue data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-md border-none"
                            >
                                My Work
                            </TabsTrigger>
                            <TabsTrigger
                                value="contact"
                                className="rounded-lg font-bold transition-all duration-200 text-stat-blue data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-md border-none"
                            >
                                Contact
                            </TabsTrigger>
                        </TabsList>

                        <TabsContent value="info" className="mt-4">
                            <Card className="shadow-card">
                                <CardHeader>
                                    <CardTitle className="text-lg">Business Information</CardTitle>
                                    <CardDescription>
                                        Basic details about your business
                                    </CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="businessName">Business Name</Label>
                                        <Input
                                            id="businessName"
                                            value={businessName}
                                            onChange={(e) => setBusinessName(e.target.value)}
                                        />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="tagline">Tagline</Label>
                                        <Input
                                            id="tagline"
                                            value={tagline}
                                            onChange={(e) => setTagline(e.target.value)}
                                            placeholder="A short catchy phrase"
                                        />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="description">About Us</Label>
                                        <Textarea
                                            id="description"
                                            value={description}
                                            onChange={(e) => setDescription(e.target.value)}
                                            className="min-h-[120px]"
                                            placeholder="Tell your customers about your business..."
                                        />
                                    </div>
                                    <Button onClick={handleSave} className="w-full gap-2 bg-primary-gradient text-white">
                                        <Save className="w-4 h-4" />
                                        Save Changes
                                    </Button>
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="services" className="mt-4">
                            <Card className="shadow-card">
                                <CardHeader className="flex flex-row items-center justify-between">
                                    <div>
                                        <CardTitle className="text-lg">Services</CardTitle>
                                        <CardDescription>
                                            Manage services displayed on your landing page
                                        </CardDescription>
                                    </div>
                                    <Button size="sm" onClick={addService} className="gap-1 bg-primary-gradient text-white">
                                        <Plus className="w-4 h-4" />
                                        Add
                                    </Button>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                    {services.map((service) => (
                                        <div
                                            key={service.id}
                                            className="flex items-center gap-3 p-3 rounded-lg bg-muted/50 border"
                                        >
                                            <div className="flex-1 grid grid-cols-3 gap-2">
                                                <Input
                                                    value={service.name}
                                                    onChange={(e) => updateService(service.id, 'name', e.target.value)}
                                                    placeholder="Service name"
                                                    className="text-sm"
                                                />
                                                <Input
                                                    value={service.duration}
                                                    onChange={(e) => updateService(service.id, 'duration', e.target.value)}
                                                    placeholder="Duration"
                                                    className="text-sm"
                                                />
                                                <Input
                                                    value={service.price}
                                                    onChange={(e) => updateService(service.id, 'price', e.target.value)}
                                                    placeholder="Price"
                                                    className="text-sm"
                                                />
                                            </div>
                                            <Button
                                                size="icon"
                                                variant="ghost"
                                                className="shrink-0 text-muted-foreground hover:text-destructive"
                                                onClick={() => removeService(service.id)}
                                            >
                                                <X className="w-4 h-4" />
                                            </Button>
                                        </div>
                                    ))}
                                    <Button onClick={handleSave} className="w-full gap-2 mt-4 bg-primary-gradient text-white">
                                        <Save className="w-4 h-4" />
                                        Save Services
                                    </Button>
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="mywork" className="mt-4">
                            <Card className="shadow-card">
                                <CardHeader className="flex flex-row items-center justify-between">
                                    <div>
                                        <CardTitle className="text-lg">My Work Gallery</CardTitle>
                                        <CardDescription>
                                            Showcase your best work to attract customers
                                        </CardDescription>
                                    </div>
                                    <Button size="sm" onClick={addPhoto} className="gap-1 bg-primary-gradient text-white">
                                        <Upload className="w-4 h-4" />
                                        Upload
                                    </Button>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                                        {workPhotos.map((photo) => (
                                            <div
                                                key={photo.id}
                                                className="relative group rounded-lg overflow-hidden border bg-muted"
                                            >
                                                <div className="aspect-square">
                                                    <img
                                                        src={photo.url}
                                                        alt={photo.caption}
                                                        className="w-full h-full object-cover"
                                                    />
                                                </div>
                                                <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                    <Button
                                                        size="icon"
                                                        variant="destructive"
                                                        className="h-8 w-8"
                                                        onClick={() => removePhoto(photo.id)}
                                                    >
                                                        <Trash2 className="w-4 h-4" />
                                                    </Button>
                                                </div>
                                                <div className="p-2">
                                                    <Input
                                                        value={photo.caption}
                                                        onChange={(e) => updatePhotoCaption(photo.id, e.target.value)}
                                                        placeholder="Add caption..."
                                                        className="text-xs h-8"
                                                    />
                                                </div>
                                            </div>
                                        ))}

                                        {/* Add Photo Placeholder */}
                                        <div
                                            onClick={addPhoto}
                                            className="aspect-square rounded-lg border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center gap-2 cursor-pointer hover:border-primary hover:bg-muted/50 transition-colors"
                                        >
                                            <Camera className="w-8 h-8 text-muted-foreground" />
                                            <span className="text-xs text-muted-foreground">Add Photo</span>
                                        </div>
                                    </div>
                                    <Button onClick={handleSave} className="w-full gap-2 mt-4 bg-primary-gradient text-white">
                                        <Save className="w-4 h-4" />
                                        Save Gallery
                                    </Button>
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="contact" className="mt-4">
                            <Card className="shadow-card">
                                <CardHeader>
                                    <CardTitle className="text-lg">Contact Information</CardTitle>
                                    <CardDescription>
                                        How customers can reach you
                                    </CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="phone">Phone Number</Label>
                                        <div className="relative">
                                            <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                                            <Input
                                                id="phone"
                                                value={phone}
                                                onChange={(e) => setPhone(e.target.value)}
                                                className="pl-10"
                                            />
                                        </div>
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="email">Email Address</Label>
                                        <div className="relative">
                                            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                                            <Input
                                                id="email"
                                                value={email}
                                                onChange={(e) => setEmail(e.target.value)}
                                                className="pl-10"
                                            />
                                        </div>
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="address">Address</Label>
                                        <div className="relative">
                                            <MapPin className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" />
                                            <Textarea
                                                id="address"
                                                value={address}
                                                onChange={(e) => setAddress(e.target.value)}
                                                className="pl-10 min-h-[80px]"
                                            />
                                        </div>
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="hours">Business Hours</Label>
                                        <div className="relative">
                                            <Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                                            <Input
                                                id="hours"
                                                value={hours}
                                                onChange={(e) => setHours(e.target.value)}
                                                className="pl-10"
                                            />
                                        </div>
                                    </div>
                                    <Button onClick={handleSave} className="w-full gap-2 bg-primary-gradient text-white">
                                        <Save className="w-4 h-4" />
                                        Save Contact Info
                                    </Button>
                                </CardContent>
                            </Card>
                        </TabsContent>
                    </Tabs>
                </div>

                {/* Preview Panel */}
                <div className="xl:sticky xl:top-6">
                    <Card className="shadow-card overflow-hidden">
                        <CardHeader className="bg-muted/30 border-b">
                            <div className="flex items-center justify-between">
                                <CardTitle className="text-lg flex items-center gap-2">
                                    <Eye className="w-5 h-5 font-semibold text-primary-gradient" />
                                    Live Preview
                                </CardTitle>
                                <Badge variant="secondary" className="gap-1 border-none bg-stat-blue-bg text-stat-blue">
                                    <Globe className="w-3 h-3" />
                                    {subdomain}.readyreception.com
                                </Badge>
                            </div>
                        </CardHeader>
                        <CardContent className="p-0">
                            <div className="preview-frame m-4 h-[600px] overflow-y-auto rounded-lg border shadow-inner bg-white">
                                {/* Preview Website Content */}
                                <div className="min-h-full">
                                    {/* Hero Section */}
                                    <div className="bg-primary-gradient text-white p-8 text-center">
                                        <div className="w-20 h-20 rounded-full bg-white/20 mx-auto mb-4 flex items-center justify-center">
                                            <Scissors className="w-10 h-10" />
                                        </div>
                                        <h1 className="text-2xl font-bold mb-2">{businessName}</h1>
                                        <p className="text-white/80 text-sm">{tagline}</p>
                                        <button className="mt-6 bg-white text-stat-blue px-8 py-2.5 rounded-full text-sm font-bold shadow-lg hover:bg-gray-50 transition-colors">
                                            Book Now
                                        </button>
                                    </div>

                                    {/* About Section */}
                                    <div className="p-6">
                                        <h2 className="text-lg font-bold mb-3 text-gray-800">About Us</h2>
                                        <p className="text-sm text-gray-600 leading-relaxed">{description}</p>
                                    </div>

                                    {/* Services Section */}
                                    <div className="p-6 bg-gray-50/50 border-y">
                                        <h2 className="text-lg font-bold mb-4 text-gray-800">Our Services</h2>
                                        <div className="space-y-3">
                                            {services.map((service) => (
                                                <div
                                                    key={service.id}
                                                    className="flex items-center justify-between p-4 bg-white rounded-xl shadow-sm border border-gray-100"
                                                >
                                                    <div>
                                                        <p className="font-bold text-sm text-gray-800">{service.name}</p>
                                                        <p className="text-xs text-gray-500 mt-0.5">{service.duration}</p>
                                                    </div>
                                                    <p className="font-bold text-stat-blue">{service.price}</p>
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    {/* My Work Gallery Section */}
                                    {workPhotos.length > 0 && (
                                        <div className="p-6">
                                            <h2 className="text-lg font-bold mb-4 flex items-center gap-2 text-gray-800">
                                                <Camera className="w-5 h-5 text-stat-blue" />
                                                Our Work
                                            </h2>
                                            <div className="grid grid-cols-3 gap-3">
                                                {workPhotos.slice(0, 6).map((photo) => (
                                                    <div key={photo.id} className="aspect-square rounded-xl overflow-hidden shadow-sm">
                                                        <img
                                                            src={photo.url}
                                                            alt={photo.caption}
                                                            className="w-full h-full object-cover"
                                                        />
                                                    </div>
                                                ))}
                                            </div>
                                            {workPhotos.length > 6 && (
                                                <p className="text-xs text-center text-gray-500 mt-3 font-medium">
                                                    +{workPhotos.length - 6} more photos
                                                </p>
                                            )}
                                        </div>
                                    )}

                                    {/* Contact Section */}
                                    <div className="p-6 bg-gray-50/50 border-t">
                                        <h2 className="text-lg font-bold mb-4 text-gray-800">Contact Us</h2>
                                        <div className="space-y-4 text-sm">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-lg bg-stat-blue/10 flex items-center justify-center text-stat-blue">
                                                    <Phone className="w-4 h-4" />
                                                </div>
                                                <span className="text-gray-600 font-medium">{phone}</span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-lg bg-rose-500/10 flex items-center justify-center text-rose-500">
                                                    <Mail className="w-4 h-4" />
                                                </div>
                                                <span className="text-gray-600 font-medium">{email}</span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-lg bg-stat-emerald/10 flex items-center justify-center text-stat-emerald">
                                                    <MapPin className="w-4 h-4" />
                                                </div>
                                                <span className="text-gray-600 font-medium">{address}</span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-lg bg-amber-500/10 flex items-center justify-center text-amber-500">
                                                    <Clock className="w-4 h-4" />
                                                </div>
                                                <span className="text-gray-600 font-medium">{hours}</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Footer */}
                                    <div className="p-6 bg-gray-900 text-white/60 text-center text-[10px] tracking-wider uppercase font-bold">
                                        <p>Powered by Ready Reception</p>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    );
};
