"use client";

import { useState, useCallback } from "react";
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 { CheckCircle, Clock } from "lucide-react";
import {
  publicContactRequestSchema,
  type PublicContactRequest,
} from "@customer-portal/domain/support";
import { apiClient } from "@/core/api";
import { cn } from "@/shared/utils";

interface ContactFormProps {
  className?: string;
}

function ContactFormSuccess({ className }: { className: string | undefined }) {
  return (
    <div className={cn("text-center py-12", className)}>
      <div className="w-16 h-16 bg-success/10 rounded-full flex items-center justify-center mx-auto mb-4">
        <CheckCircle className="h-8 w-8 text-success" />
      </div>
      <h3 className="text-2xl font-bold text-foreground mb-2">Message Sent!</h3>
      <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-3 justify-center">
        <Button as="a" href="/" variant="outline" size="sm">
          Back to Home
        </Button>
        <Button as="a" href="/services" size="sm">
          Browse Services
        </Button>
      </div>
    </div>
  );
}

export function ContactForm({ className }: ContactFormProps) {
  const [isSubmitted, setIsSubmitted] = useState(false);

  const handleSubmit = useCallback(async (data: PublicContactRequest) => {
    await apiClient.POST("/api/support/contact", { body: data });
    setIsSubmitted(true);
  }, []);

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

  if (isSubmitted) return <ContactFormSuccess className={className} />;

  return (
    <div className={cn("bg-card rounded-2xl border border-border/60 p-5 sm:p-6", className)}>
      {form.submitError && (
        <AlertBanner variant="error" title="Error" className="mb-6">
          {form.submitError}
        </AlertBanner>
      )}

      <form onSubmit={event => void form.handleSubmit(event)} className="space-y-4">
        <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>

        <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="Message"
          error={form.touched["message"] ? form.errors["message"] : undefined}
          required
        >
          <textarea
            className="flex min-h-[100px] w-full rounded-lg border border-input bg-muted/20 px-3.5 py-2.5 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-all 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>

      <div className="flex items-center gap-2 text-xs text-muted-foreground mt-4 pt-3 border-t border-border/40">
        <Clock className="h-3.5 w-3.5 shrink-0" />
        <span>We typically respond within 24 hours.</span>
      </div>
    </div>
  );
}
