"use client";

import { useState } from "react";
import {
  Mail,
  Phone,
  MapPin,
  Clock,
  Save,
  Globe,
  X,
  Eye,
  MapPinned,
  ExternalLink,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { cn } from "@/lib/utils";

// ─── Types ───────────────────────────────────────────────────────────────────

interface ContactSettings {
  // Basic Information
  pageTitle: string;
  pageDescription: string;
  // Contact Methods
  visitTitle: string;
  visitAddress: string;
  callTitle: string;
  callNumber: string;
  emailTitle: string;
  emailAddress: string;
  emailBadge: boolean;
  workingHoursTitle: string;
  workingHoursDetail: string;
  // Location Map
  enableMap: boolean;
  mapEmbedUrl: string;
}

// ─── Default Data ────────────────────────────────────────────────────────────

const DEFAULT_SETTINGS: ContactSettings = {
  pageTitle: "Contact Us",
  pageDescription:
    "We'd love to hear from you. Please reach out using any of the methods below.",
  visitTitle: "Office Location",
  visitAddress: "123, MG Road, Sector 14\nGurgaon, Haryana 122001",
  callTitle: "Phone Support",
  callNumber: "+91 98765 43210",
  emailTitle: "General Inquiries",
  emailAddress: "hello@teertham.com",
  emailBadge: true,
  workingHoursTitle: "Operating Hours",
  workingHoursDetail: "Mon - Fri: 9:00 AM - 6:00 PM",
  enableMap: true,
  mapEmbedUrl:
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3507.0!2d77.02!3d28.46!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zMjjCsDI3JzM2LjAiTiA3N8KwMDEnMTIuMCJF!5e0!3m2!1sen!2sin!4v1234567890",
};

// ─── Main Component ──────────────────────────────────────────────────────────

export function ContactSettingsClient() {
  const [settings, setSettings] = useState<ContactSettings>(DEFAULT_SETTINGS);
  const [showPreview, setShowPreview] = useState(true);
  const toast = useToastEnhanced();

  const updateField = <K extends keyof ContactSettings>(
    key: K,
    value: ContactSettings[K]
  ) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    toast.success({
      title: "Contact settings saved",
      description: "All contact page settings have been updated successfully.",
    });
  };

  const handleCancel = () => {
    setSettings(DEFAULT_SETTINGS);
    toast.info({
      title: "Changes discarded",
      description: "Settings have been reset to their previous values.",
    });
  };

  return (
    <section aria-labelledby="contact-settings-title" className="admin-section">
      {/* Header */}
      <header className="admin-page-header">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <div>
            <h1 id="contact-settings-title" className="admin-page-title">
              Contact Settings
            </h1>
            <p className="admin-page-description">
              Configure the contact page content, methods, and location map.
            </p>
          </div>
          <Button
            variant="outline"
            size="sm"
            className="gap-2 rounded-xl"
            onClick={() => setShowPreview(!showPreview)}
          >
            <Eye className="h-4 w-4" />
            {showPreview ? "Hide Preview" : "Show Preview"}
          </Button>
        </div>
      </header>

      {/* Split Layout */}
      <div className="flex gap-0 rounded-xl border border-border bg-card overflow-hidden min-h-[700px]">
        {/* ─── LEFT PANEL: Settings Form ─────────────── */}
        <div
          className={cn(
            "flex flex-col overflow-y-auto",
            showPreview ? "w-full lg:w-[55%] xl:w-[50%]" : "w-full"
          )}
        >
          {/* Panel Header */}
          <div className="flex items-center gap-2 px-5 py-3 border-b border-border bg-muted/30">
            <Mail className="h-4 w-4 text-primary" />
            <h2 className="text-sm font-semibold">Contact Settings</h2>
          </div>

          <div className="p-5 space-y-8 flex-1">
            {/* ─── Basic Information ─────────────────── */}
            <div className="space-y-4">
              <div>
                <h3 className="text-sm font-semibold">Basic Information</h3>
                <p className="text-xs text-muted-foreground mt-0.5">
                  General details for the contact page
                </p>
              </div>
              <Separator />

              <div className="space-y-4">
                <div className="space-y-2">
                  <Label
                    htmlFor="page-title"
                    className="text-xs font-medium text-muted-foreground"
                  >
                    Title
                  </Label>
                  <Input
                    id="page-title"
                    placeholder="Contact Us"
                    value={settings.pageTitle}
                    onChange={(e) => updateField("pageTitle", e.target.value)}
                    className="rounded-lg"
                  />
                </div>

                <div className="space-y-2">
                  <Label
                    htmlFor="page-description"
                    className="text-xs font-medium text-muted-foreground"
                  >
                    Description
                  </Label>
                  <Textarea
                    id="page-description"
                    placeholder="Enter a description for the contact page..."
                    value={settings.pageDescription}
                    onChange={(e) =>
                      updateField("pageDescription", e.target.value)
                    }
                    className="rounded-lg min-h-[100px] resize-none"
                    rows={4}
                  />
                </div>
              </div>
            </div>

            {/* ─── Contact Methods ──────────────────── */}
            <div className="space-y-4">
              <div>
                <h3 className="text-sm font-semibold">Contact Methods</h3>
                <p className="text-xs text-muted-foreground mt-0.5">
                  Configure how visitors can reach you
                </p>
              </div>
              <Separator />

              <div className="space-y-3">
                {/* Visit / Address */}
                <div className="grid grid-cols-2 gap-4 p-4 rounded-lg border border-border/60 bg-muted/20">
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Visit On (Title)
                    </Label>
                    <Input
                      placeholder="Office Location"
                      value={settings.visitTitle}
                      onChange={(e) =>
                        updateField("visitTitle", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Visit On Detail (Address)
                    </Label>
                    <Input
                      placeholder="123 Business Avenue, Suite 45"
                      value={settings.visitAddress}
                      onChange={(e) =>
                        updateField("visitAddress", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                </div>

                {/* Call / Phone */}
                <div className="grid grid-cols-2 gap-4 p-4 rounded-lg border border-border/60 bg-muted/20">
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Call On (Title)
                    </Label>
                    <Input
                      placeholder="Phone Support"
                      value={settings.callTitle}
                      onChange={(e) => updateField("callTitle", e.target.value)}
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Call On Detail (Number)
                    </Label>
                    <Input
                      placeholder="+1 (555) 123-4567"
                      value={settings.callNumber}
                      onChange={(e) =>
                        updateField("callNumber", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                </div>

                {/* Email */}
                <div className="grid grid-cols-2 gap-4 p-4 rounded-lg border border-border/60 bg-muted/20">
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Label className="text-xs font-medium text-muted-foreground">
                        Email On (Title)
                      </Label>
                      {settings.emailBadge && (
                        <Badge
                          variant="default"
                          className="text-[9px] px-1.5 py-0 h-4 rounded-md"
                        >
                          i
                        </Badge>
                      )}
                    </div>
                    <Input
                      placeholder="General Inquiries"
                      value={settings.emailTitle}
                      onChange={(e) =>
                        updateField("emailTitle", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Label className="text-xs font-medium text-muted-foreground">
                        Email On Detail (Email Address)
                      </Label>
                      {settings.emailBadge && (
                        <Badge
                          variant="default"
                          className="text-[9px] px-1.5 py-0 h-4 rounded-md"
                        >
                          i
                        </Badge>
                      )}
                    </div>
                    <Input
                      type="email"
                      placeholder="hello@company.com"
                      value={settings.emailAddress}
                      onChange={(e) =>
                        updateField("emailAddress", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                </div>

                {/* Working Hours */}
                <div className="grid grid-cols-2 gap-4 p-4 rounded-lg border border-border/60 bg-muted/20">
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Working Hours (Title)
                    </Label>
                    <Input
                      placeholder="Operating Hours"
                      value={settings.workingHoursTitle}
                      onChange={(e) =>
                        updateField("workingHoursTitle", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Working Hours Detail
                    </Label>
                    <Input
                      placeholder="Mon - Fri: 9:00 AM - 6:00 PM"
                      value={settings.workingHoursDetail}
                      onChange={(e) =>
                        updateField("workingHoursDetail", e.target.value)
                      }
                      className="rounded-lg h-9 text-sm"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* ─── Location Map ─────────────────────── */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-semibold">Location Map</h3>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    Embed a Google Maps iframe to show your location
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Label htmlFor="enable-map" className="text-xs font-medium">
                    Enable Map
                  </Label>
                  <Switch
                    id="enable-map"
                    checked={settings.enableMap}
                    onCheckedChange={(checked) =>
                      updateField("enableMap", checked)
                    }
                  />
                </div>
              </div>
              <Separator />

              <div className="space-y-4">
                <div className="space-y-2">
                  <Label
                    htmlFor="map-url"
                    className="text-xs font-medium text-muted-foreground"
                  >
                    Google Maps Embed Link (iframe URL)
                  </Label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                    <Input
                      id="map-url"
                      placeholder="https://www.google.com/maps/embed?pb=..."
                      value={settings.mapEmbedUrl}
                      onChange={(e) =>
                        updateField("mapEmbedUrl", e.target.value)
                      }
                      className="rounded-lg pl-9 text-sm"
                      disabled={!settings.enableMap}
                    />
                  </div>
                </div>

                {settings.enableMap && settings.mapEmbedUrl && (
                  <div className="space-y-2">
                    <Label className="text-xs font-medium text-muted-foreground">
                      Preview
                    </Label>
                    <div className="rounded-lg overflow-hidden border border-border bg-muted/30">
                      <iframe
                        src={settings.mapEmbedUrl}
                        width="100%"
                        height="200"
                        style={{ border: 0 }}
                        allowFullScreen
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                        title="Office location map preview"
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Footer Actions */}
          <div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-border bg-muted/20">
            <Button
              variant="outline"
              className="rounded-xl"
              onClick={handleCancel}
            >
              Cancel
            </Button>
            <Button
              className="rounded-xl shadow-lg shadow-primary/25"
              onClick={handleSave}
            >
              <Save className="h-4 w-4 mr-2" aria-hidden="true" />
              Save Settings
            </Button>
          </div>
        </div>

        {/* ─── RIGHT PANEL: Preview ─────────────── */}
        {showPreview && (
          <div className="hidden lg:flex flex-col w-[45%] xl:w-[50%] overflow-y-auto border-l border-border">
            {/* Preview Header */}
            <div className="flex items-center justify-between px-5 py-3 border-b border-border bg-muted/20">
              <div className="flex items-center gap-2">
                <Eye className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold">Live Preview</h3>
              </div>
              <Button
                variant="ghost"
                size="sm"
                className="h-7 w-7 p-0"
                onClick={() => setShowPreview(false)}
                title="Close preview"
              >
                <X className="h-3.5 w-3.5" />
              </Button>
            </div>

            {/* Preview Content */}
            <div className="flex-1 p-8 bg-[#f2f7f7] overflow-y-auto">
              {/* Page Title Preview */}
              <div className="text-center mb-10">
                <h2 className="text-3xl font-bold tracking-tight text-slate-800">
                  <span className="text-slate-800">Get in </span>
                  <span className="text-teal-800">Touch</span>
                </h2>
                <p className="text-sm text-slate-500 mt-4 max-w-lg mx-auto leading-relaxed">
                  Have questions or need assistance? We're here to help you
                  24/7. Reach out and let's make your travel experience
                  unforgettable.
                </p>
              </div>

              {/* Contact Methods Preview */}
              <div className="grid grid-cols-2 2xl:grid-cols-4 gap-4 mb-8">
                {/* Visit Card */}
                <div className="flex flex-col items-center text-center rounded-2xl bg-white p-6 shadow-sm border border-transparent transition-all hover:shadow-md">
                  <div className="h-10 w-10 mb-4 rounded-xl bg-teal-50 flex items-center justify-center">
                    <MapPin className="h-5 w-5 text-teal-800" />
                  </div>
                  <h3 className="text-sm font-bold text-slate-800 mb-2">
                    {settings.visitTitle || "Visit Us"}
                  </h3>
                  <p className="text-[11px] text-slate-500 font-medium whitespace-pre-line leading-relaxed">
                    {settings.visitAddress ||
                      "123 Ameera Holidays Street, Mumbai\nMaharashtra 400001, India"}
                  </p>
                </div>

                {/* Call Card */}
                <div className="flex flex-col items-center text-center rounded-2xl bg-white p-6 shadow-sm border border-transparent transition-all hover:shadow-md">
                  <div className="h-10 w-10 mb-4 rounded-xl bg-teal-50 flex items-center justify-center">
                    <Phone className="h-5 w-5 text-teal-800" />
                  </div>
                  <h3 className="text-sm font-bold text-slate-800 mb-2">
                    {settings.callTitle || "Call Us"}
                  </h3>
                  <div className="text-[11px] text-slate-500 font-medium leading-relaxed">
                    <p className="text-slate-800 font-bold mb-1">
                      {settings.callNumber || "+91 85059 99770"}
                    </p>
                    <p>Mon-Sun, 24/7 Support</p>
                  </div>
                </div>

                {/* Email Card */}
                <div className="flex flex-col items-center text-center rounded-2xl bg-white p-6 shadow-sm border border-transparent transition-all hover:shadow-md">
                  <div className="h-10 w-10 mb-4 rounded-xl bg-teal-50 flex items-center justify-center">
                    <Mail className="h-5 w-5 text-teal-800 stroke-[1.5]" />
                  </div>
                  <h3 className="text-sm font-bold text-slate-800 mb-2">
                    {settings.emailTitle || "Email Us"}
                  </h3>
                  <div className="text-[11px] text-slate-500 font-medium leading-relaxed">
                    <p className="mb-1">
                      {settings.emailAddress || "info@ameeraholidays.com"}
                    </p>
                    <p>info@ameeraholidays.com</p>
                  </div>
                </div>

                {/* Working Hours Card */}
                <div className="flex flex-col items-center text-center rounded-2xl bg-white p-6 shadow-sm border border-transparent transition-all hover:shadow-md">
                  <div className="h-10 w-10 mb-4 rounded-xl bg-teal-50 flex items-center justify-center">
                    <Clock className="h-5 w-5 text-teal-800" />
                  </div>
                  <h3 className="text-sm font-bold text-slate-800 mb-2">
                    {settings.workingHoursTitle || "Working Hours"}
                  </h3>
                  <div className="text-[11px] text-slate-500 font-medium leading-relaxed">
                    <p className="mb-1 text-slate-800 font-bold">
                      {settings.workingHoursDetail || "24/7 Available"}
                    </p>
                    <p>Always Here to Help</p>
                  </div>
                </div>
              </div>

              {/* Map Preview */}
              {settings.enableMap && settings.mapEmbedUrl && (
                <div className="space-y-3 mt-8">
                  <div className="flex items-center justify-center gap-2 mb-4">
                    <MapPinned className="h-4 w-4 text-teal-800" />
                    <h4 className="text-sm font-bold text-slate-800">
                      Our Location
                    </h4>
                  </div>
                  <div className="rounded-2xl overflow-hidden shadow-sm bg-white p-2">
                    <div className="rounded-xl overflow-hidden">
                      <iframe
                        src={settings.mapEmbedUrl}
                        width="100%"
                        height="200"
                        style={{ border: 0 }}
                        allowFullScreen
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                        title="Office location map"
                      />
                    </div>
                  </div>
                </div>
              )}

              {!settings.enableMap && (
                <div className="flex flex-col items-center justify-center py-8 text-slate-400 rounded-2xl border border-dashed border-slate-300 mt-8">
                  <MapPin className="h-8 w-8 mb-2 opacity-40" />
                  <p className="text-sm font-medium">Map is disabled</p>
                  <p className="text-xs mt-1">
                    Enable the map toggle to show location
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
