"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 } from "lucide-react";
import {
  publicContactRequestSchema,
  type PublicContactRequest,
} from "@customer-portal/domain/support";
import { apiClient, ApiError, isApiError } from "@/core/api";

const SEND_ERROR_MESSAGE = "Failed to send message";

/**
 * PublicContactView - Contact page with form, phone, chat, and location info
 */
export function PublicContactView() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [submitError, setSubmitError] = useState<string | 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 || SEND_ERROR_MESSAGE);
        return;
      }
      if (error instanceof ApiError) {
        setSubmitError(error.message || SEND_ERROR_MESSAGE);
        return;
      }
      setSubmitError(error instanceof Error ? error.message : SEND_ERROR_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-12">
        <div className="w-16 h-16 bg-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
          <CheckCircle className="h-8 w-8 text-success" />
        </div>
        <h1 className="text-2xl font-bold text-foreground mb-2">Message Sent!</h1>
        <p className="text-muted-foreground mb-6">
          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="/help" variant="outline">
            Back to Support
          </Button>
          <Button as="a" href="/services">
            Browse Services
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto px-4">
      {/* Header */}
      <div className="text-center mb-16 pt-8">
        <h1 className="text-4xl sm:text-5xl font-extrabold text-foreground mb-6 tracking-tight">
          Get in Touch
        </h1>
        <p className="text-xl text-muted-foreground max-w-2xl mx-auto leading-relaxed">
          Have a question about our services? We're here to help you find the perfect solution for
          your stay in Japan.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
        {/* Left Column - Contact Form */}
        <div className="lg:col-span-7">
          <div className="bg-card rounded-2xl border border-border/60 shadow-sm overflow-hidden">
            <div className="p-6 sm:p-8 border-b border-border/60 bg-muted/20">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                  <Mail className="h-5 w-5" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-foreground">Send a Message</h2>
                  <p className="text-sm text-muted-foreground">
                    We typically reply within 24 hours
                  </p>
                </div>
              </div>
            </div>

            <div className="p-6 sm:p-8">
              {submitError && (
                <AlertBanner variant="error" title="Error" className="mb-6">
                  {submitError}
                </AlertBanner>
              )}

              <form onSubmit={event => void form.handleSubmit(event)} className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <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-background"
                    />
                  </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-background"
                    />
                  </FormField>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <FormField
                    label="Phone (Optional)"
                    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-background"
                    />
                  </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-background"
                    />
                  </FormField>
                </div>

                <FormField
                  label="Message"
                  error={form.touched["message"] ? form.errors["message"] : undefined}
                  required
                >
                  <textarea
                    className="flex min-h-[160px] w-full rounded-lg border border-input bg-background 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"
                    value={form.values.message}
                    onChange={e => form.setValue("message", e.target.value)}
                    onBlur={() => form.setTouchedField("message")}
                    placeholder="Tell us more about your inquiry..."
                    rows={5}
                  />
                </FormField>

                <Button
                  type="submit"
                  className="w-full sm:w-auto min-w-[160px]"
                  size="lg"
                  disabled={form.isSubmitting}
                  isLoading={form.isSubmitting}
                  loadingText="Sending..."
                >
                  Send Message
                </Button>
              </form>

              <p className="text-xs text-muted-foreground mt-6 pt-6 border-t border-border/60">
                By submitting this form, you agree to our{" "}
                <Link href="#" className="text-primary hover:underline font-medium">
                  Privacy Policy
                </Link>
                . Your information is secure and will only be used to respond to your inquiry.
              </p>
            </div>
          </div>
        </div>

        {/* Right Column - Contact Info */}
        <div className="lg:col-span-5 space-y-6">
          {/* By Phone */}
          <div className="bg-card rounded-2xl border border-border/60 p-6 sm:p-8 hover:border-primary/30 transition-colors duration-300">
            <h2 className="text-xl font-bold text-foreground mb-4">Phone Support</h2>
            <div className="space-y-4">
              <div>
                <div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">
                  Japan (Toll Free)
                </div>
                <a
                  href="tel:0120-660-470"
                  className="text-2xl font-bold text-foreground hover:text-primary transition-colors inline-block"
                >
                  0120-660-470
                </a>
              </div>
              <div>
                <div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">
                  International
                </div>
                <a
                  href="tel:+81-3-3560-1006"
                  className="text-lg font-semibold text-foreground hover:text-primary transition-colors inline-block"
                >
                  +81-3-3560-1006
                </a>
              </div>
              <div className="text-sm text-muted-foreground pt-4 border-t border-border/60">
                9:30 - 18:00 JST (Mon - Fri)
              </div>
            </div>
          </div>

          {/* By Chat */}
          <div className="bg-card rounded-2xl border border-border/60 p-6 sm:p-8 hover:border-blue-500/30 transition-colors duration-300">
            <h2 className="text-xl font-bold text-foreground mb-4">Live Chat</h2>
            <p className="text-muted-foreground mb-6">
              Need quick answers? Chat with our support team directly in your browser.
            </p>
            <Button
              variant="outline"
              className="w-full justify-start"
              onClick={() => {
                /* Trigger chat logic would go here */
              }}
            >
              <span className="flex items-center gap-2">
                <span className="relative flex h-2 w-2 mr-1">
                  <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>
                Chat Available
              </span>
            </Button>
          </div>

          {/* Access / Location */}
          <div className="bg-card rounded-2xl border border-border/60 p-6 sm:p-8 hover:border-primary/30 transition-colors duration-300">
            <div className="flex items-center gap-3 mb-6">
              <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                <MapPin className="h-5 w-5" />
              </div>
              <h2 className="text-xl font-bold text-foreground">Visit Us</h2>
            </div>
            <div className="space-y-4">
              <address className="text-muted-foreground leading-relaxed not-italic">
                3F Azabu Maruka Bldg., 3-8-2 Higashi Azabu,
                <br />
                Minato-ku, Tokyo 106-0044
              </address>
              <div className="pt-4 border-t border-border/60">
                <p className="text-sm text-muted-foreground">
                  Short walk from Exit 6 of Azabu-Juban Station
                  <br />
                  (Subway Oedo Line / Nanboku Line)
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default PublicContactView;
