"use client";

import { useState, useCallback } from "react";
import Link from "next/link";
import { Button, Input } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { useZodForm } from "@/shared/hooks";
import {
  Mail,
  CheckCircle,
  MapPin,
  Phone,
  MessageSquare,
  ChevronDown,
  Clock,
  HelpCircle,
  Send,
  ExternalLink,
} from "lucide-react";
import {
  publicContactRequestSchema,
  type PublicContactRequest,
} from "@customer-portal/domain/support";
import { apiClient, ApiError, isApiError } from "@/core/api";
import { cn } from "@/shared/utils";

const FAQ_ITEMS = [
  {
    question: "Sample Question 1?",
    answer:
      "This is a sample answer for frequently asked question 1. Replace this with actual content when available.",
  },
  {
    question: "Sample Question 2?",
    answer:
      "This is a sample answer for frequently asked question 2. Replace this with actual content when available.",
  },
  {
    question: "Sample Question 3?",
    answer:
      "This is a sample answer for frequently asked question 3. Replace this with actual content when available.",
  },
  {
    question: "Sample Question 4?",
    answer:
      "This is a sample answer for frequently asked question 4. Replace this with actual content when available.",
  },
  {
    question: "Sample Question 5?",
    answer:
      "This is a sample answer for frequently asked question 5. Replace this with actual content when available.",
  },
];

/**
 * PublicContactView - Combined Support & Contact page
 */
export function PublicContactView() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);

  const handleSubmit = useCallback(async (data: PublicContactRequest) => {
    setSubmitError(null);

    try {
      await apiClient.POST("/api/support/contact", { body: data });
      setIsSubmitted(true);
    } catch (error) {
      if (isApiError(error)) {
        setSubmitError(error.message || "Failed to send message");
        return;
      }
      if (error instanceof ApiError) {
        setSubmitError(error.message || "Failed to send message");
        return;
      }
      setSubmitError(error instanceof Error ? error.message : "Failed to send message");
    }
  }, []);

  const form = useZodForm<PublicContactRequest>({
    schema: publicContactRequestSchema,
    initialValues: {
      name: "",
      email: "",
      phone: "",
      subject: "",
      message: "",
    },
    onSubmit: handleSubmit,
  });

  if (isSubmitted) {
    return (
      <div className="max-w-lg mx-auto text-center py-16">
        <div className="w-20 h-20 bg-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
          <CheckCircle className="h-10 w-10 text-success" />
        </div>
        <h1 className="text-3xl font-bold text-foreground mb-3">Message Sent!</h1>
        <p className="text-muted-foreground mb-8 text-lg">
          Thank you for contacting us. We&apos;ll get back to you within 24 hours.
        </p>
        <div className="flex gap-4 justify-center">
          <Button as="a" href="/" variant="outline">
            Back to Home
          </Button>
          <Button as="a" href="/services">
            Browse Services
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto px-4 pb-0">
      {/* Header */}
      <div className="text-center mb-12 pt-8">
        <div className="inline-flex items-center justify-center w-16 h-16 bg-primary/10 rounded-2xl mb-4 text-primary">
          <HelpCircle className="h-8 w-8" />
        </div>
        <h1 className="text-4xl sm:text-5xl font-extrabold text-foreground mb-4 tracking-tight">
          We Speak Your Language
        </h1>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto leading-relaxed">
          Have a question about our services? Our English-speaking team is here to help. No Japanese
          required. Reach out through any channel below.
        </p>
      </div>

      {/* Quick Contact Options */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-12">
        {/* Phone */}
        <a
          href="tel:0120-660-470"
          className="group bg-white rounded-2xl border border-border/60 p-6 hover:border-primary/40 hover:shadow-md transition-all duration-200"
        >
          <div className="flex items-center gap-4">
            <div className="h-12 w-12 rounded-xl bg-primary/10 flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-colors">
              <Phone className="h-6 w-6" />
            </div>
            <div>
              <h3 className="font-bold text-foreground group-hover:text-primary transition-colors">
                Call Us
              </h3>
              <p className="text-lg font-bold text-primary">0120-660-470</p>
              <p className="text-xs text-muted-foreground">Toll-free in Japan</p>
            </div>
          </div>
        </a>

        {/* Chat */}
        <button
          type="button"
          onClick={() => {
            /* Trigger chat */
          }}
          className="group bg-white rounded-2xl border border-border/60 p-6 hover:border-blue-500/40 hover:shadow-md transition-all duration-200 text-left"
        >
          <div className="flex items-center gap-4">
            <div className="h-12 w-12 rounded-xl bg-blue-500/10 flex items-center justify-center text-blue-500 group-hover:bg-blue-500 group-hover:text-white transition-colors">
              <MessageSquare className="h-6 w-6" />
            </div>
            <div>
              <h3 className="font-bold text-foreground group-hover:text-blue-500 transition-colors">
                Live Chat
              </h3>
              <div className="flex items-center gap-2">
                <span className="relative flex h-2 w-2">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-success opacity-75"></span>
                  <span className="relative inline-flex rounded-full h-2 w-2 bg-success"></span>
                </span>
                <span className="text-sm text-muted-foreground">Available now</span>
              </div>
            </div>
          </div>
        </button>

        {/* Email */}
        <a
          href="mailto:support@assist-solutions.jp"
          className="group bg-white rounded-2xl border border-border/60 p-6 hover:border-emerald-500/40 hover:shadow-md transition-all duration-200"
        >
          <div className="flex items-center gap-4">
            <div className="h-12 w-12 rounded-xl bg-emerald-500/10 flex items-center justify-center text-emerald-500 group-hover:bg-emerald-500 group-hover:text-white transition-colors">
              <Mail className="h-6 w-6" />
            </div>
            <div>
              <h3 className="font-bold text-foreground group-hover:text-emerald-500 transition-colors">
                Email Us
              </h3>
              <p className="text-sm text-muted-foreground">support@assist-solutions.jp</p>
            </div>
          </div>
        </a>
      </div>

      {/* Business Hours Banner */}
      <div className="bg-muted/30 rounded-xl p-4 mb-12 flex items-center justify-center gap-3 text-sm">
        <Clock className="h-4 w-4 text-muted-foreground" />
        <span className="text-muted-foreground">
          <span className="font-medium text-foreground">Business Hours:</span> Mon - Fri, 9:30 AM -
          6:00 PM JST
        </span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 mb-16">
        {/* FAQ Section */}
        <div>
          <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-2">
            <HelpCircle className="h-6 w-6 text-primary" />
            Frequently Asked Questions
          </h2>
          <div className="space-y-3">
            {FAQ_ITEMS.map((item, index) => {
              const isExpanded = expandedFaq === index;
              return (
                <div
                  key={index}
                  className="bg-white rounded-xl border border-border/60 overflow-hidden"
                >
                  <button
                    type="button"
                    onClick={() => setExpandedFaq(isExpanded ? null : index)}
                    className="w-full flex items-center justify-between p-4 text-left hover:bg-muted/30 transition-colors"
                  >
                    <span className="font-medium text-foreground text-sm pr-4">
                      {item.question}
                    </span>
                    <ChevronDown
                      className={cn(
                        "h-4 w-4 text-muted-foreground flex-shrink-0 transition-transform",
                        isExpanded && "rotate-180"
                      )}
                    />
                  </button>
                  {isExpanded && (
                    <div className="px-4 pb-4">
                      <p className="text-sm text-muted-foreground leading-relaxed">{item.answer}</p>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Contact Form */}
        <div>
          <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-2">
            <Send className="h-6 w-6 text-primary" />
            Send a Message
          </h2>
          <div className="bg-white rounded-2xl border border-border/60 p-6">
            {submitError && (
              <AlertBanner variant="error" title="Error" className="mb-6">
                {submitError}
              </AlertBanner>
            )}

            <form onSubmit={event => void form.handleSubmit(event)} className="space-y-5">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                <FormField
                  label="Name"
                  error={form.touched["name"] ? form.errors["name"] : undefined}
                  required
                >
                  <Input
                    value={form.values.name}
                    onChange={e => form.setValue("name", e.target.value)}
                    onBlur={() => form.setTouchedField("name")}
                    placeholder="Your name"
                    className="bg-muted/20"
                  />
                </FormField>

                <FormField
                  label="Email"
                  error={form.touched["email"] ? form.errors["email"] : undefined}
                  required
                >
                  <Input
                    type="email"
                    value={form.values.email}
                    onChange={e => form.setValue("email", e.target.value)}
                    onBlur={() => form.setTouchedField("email")}
                    placeholder="your@email.com"
                    className="bg-muted/20"
                  />
                </FormField>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                <FormField
                  label="Phone"
                  error={form.touched["phone"] ? form.errors["phone"] : undefined}
                >
                  <Input
                    value={form.values.phone ?? ""}
                    onChange={e => form.setValue("phone", e.target.value)}
                    onBlur={() => form.setTouchedField("phone")}
                    placeholder="+81 90-1234-5678"
                    className="bg-muted/20"
                  />
                </FormField>

                <FormField
                  label="Subject"
                  error={form.touched["subject"] ? form.errors["subject"] : undefined}
                  required
                >
                  <Input
                    value={form.values.subject}
                    onChange={e => form.setValue("subject", e.target.value)}
                    onBlur={() => form.setTouchedField("subject")}
                    placeholder="How can we help?"
                    className="bg-muted/20"
                  />
                </FormField>
              </div>

              <FormField
                label="Message"
                error={form.touched["message"] ? form.errors["message"] : undefined}
                required
              >
                <textarea
                  className="flex min-h-[120px] w-full rounded-lg border border-input bg-muted/20 px-4 py-3 text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:border-transparent disabled:cursor-not-allowed disabled:opacity-50 transition-colors resize-y text-sm"
                  value={form.values.message}
                  onChange={e => form.setValue("message", e.target.value)}
                  onBlur={() => form.setTouchedField("message")}
                  placeholder="Tell us more about your inquiry..."
                  rows={4}
                />
              </FormField>

              <Button
                type="submit"
                className="w-full"
                size="lg"
                disabled={form.isSubmitting}
                isLoading={form.isSubmitting}
                loadingText="Sending..."
              >
                Send Message
              </Button>
            </form>

            <p className="text-xs text-muted-foreground mt-4 pt-4 border-t border-border/60">
              By submitting, you agree to our{" "}
              <Link href="#" className="text-primary hover:underline">
                Privacy Policy
              </Link>
              . We typically respond within 24 hours.
            </p>
          </div>
        </div>
      </div>

      {/* Office Location */}
      <div className="bg-white rounded-2xl border border-border/60 overflow-hidden">
        <div className="grid grid-cols-1 lg:grid-cols-2">
          {/* Map */}
          <div className="h-[300px] lg:h-auto">
            <iframe
              title="Assist Solutions Corp Office"
              src="https://www.google.com/maps?q=Assist+Solutions+Corp,+3-8-2+Higashi+Azabu,+Minato-ku,+Tokyo&output=embed"
              className="w-full h-full"
              loading="lazy"
              allowFullScreen
              referrerPolicy="no-referrer-when-downgrade"
            />
          </div>

          {/* Address Info */}
          <div className="p-8">
            <div className="flex items-center gap-3 mb-6">
              <div className="h-12 w-12 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                <MapPin className="h-6 w-6" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-foreground">Visit Our Office</h2>
                <p className="text-sm text-muted-foreground">
                  Walk-ins welcome during business hours
                </p>
              </div>
            </div>

            <div className="space-y-6">
              <div>
                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                  Address
                </h3>
                <address className="text-foreground leading-relaxed not-italic">
                  3F Azabu Maruka Bldg., 3-8-2 Higashi Azabu,
                  <br />
                  Minato-ku, Tokyo 106-0044
                </address>
              </div>

              <div>
                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                  Contact
                </h3>
                <p className="text-foreground">
                  Tel: 03-3560-1006
                  <br />
                  Fax: 03-3560-1007
                </p>
              </div>

              <div>
                <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                  Access
                </h3>
                <p className="text-sm text-muted-foreground leading-relaxed">
                  5 min walk from Exit 6 of Azabu-Juban Station
                  <br />
                  (Subway Oedo Line / Nanboku Line)
                </p>
              </div>

              <a
                href="https://www.google.com/maps/dir//Assist+Solutions+Corp,+3-8-2+Higashi+Azabu,+Minato-ku,+Tokyo"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 text-primary font-medium hover:underline"
              >
                Get Directions
                <ExternalLink className="h-4 w-4" />
              </a>
            </div>
          </div>
        </div>
      </div>

      {/* Existing Customer CTA */}
      <div className="text-center mt-12 pt-8 border-t border-border/60">
        <p className="text-muted-foreground">
          Already have an account?{" "}
          <Link
            href="/auth/login"
            className="font-semibold text-primary hover:text-primary/80 hover:underline transition-colors"
          >
            Sign in
          </Link>{" "}
          to access your dashboard and support tickets.
        </p>
      </div>
    </div>
  );
}

export default PublicContactView;
