"use client";

import { useState, type FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  PaperAirplaneIcon,
  SparklesIcon,
  ChatBubbleLeftRightIcon,
} from "@heroicons/react/24/outline";
import { TicketIcon as TicketIconSolid } from "@heroicons/react/24/solid";

import { PageLayout } from "@/components/templates/PageLayout";
import { AnimatedCard } from "@/components/molecules";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button } from "@/components/atoms";
import { useCreateCase } from "@/features/support/hooks/useCreateCase";
import { SUPPORT_CASE_PRIORITY, type SupportCasePriority } from "@customer-portal/domain/support";

export function NewSupportCaseView() {
  const router = useRouter();
  const createCaseMutation = useCreateCase();
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    subject: "",
    priority: SUPPORT_CASE_PRIORITY.MEDIUM as SupportCasePriority,
    description: "",
  });

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    setError(null);

    try {
      await createCaseMutation.mutateAsync({
        subject: formData.subject.trim(),
        description: formData.description.trim(),
        priority: formData.priority,
      });

      router.push("/account/support?created=true");
    } catch (err) {
      setError(
        process.env.NODE_ENV === "development"
          ? err instanceof Error
            ? err.message
            : "Failed to create support case"
          : "Unable to create your support case right now. Please try again."
      );
    }
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value,
    }));
  };

  const isFormValid = formData.subject.trim() && formData.description.trim();

  const priorityOptions = [
    { value: SUPPORT_CASE_PRIORITY.LOW, label: "Low - General question" },
    { value: SUPPORT_CASE_PRIORITY.MEDIUM, label: "Medium - Issue affecting work" },
    { value: SUPPORT_CASE_PRIORITY.HIGH, label: "High - Urgent / Service disruption" },
  ];

  return (
    <PageLayout
      icon={<TicketIconSolid />}
      title="Create Support Case"
      description="Get help from our support team"
      breadcrumbs={[{ label: "Support", href: "/account/support" }, { label: "Create Case" }]}
    >
      {/* AI Chat Suggestion */}
      <AnimatedCard className="overflow-hidden" variant="highlighted">
        <div className="bg-primary p-5">
          <div className="flex flex-col sm:flex-row sm:items-center gap-4">
            <div className="flex-shrink-0">
              <div className="w-12 h-12 bg-primary-foreground/10 rounded-xl flex items-center justify-center">
                <SparklesIcon className="h-6 w-6 text-primary-foreground" />
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-lg font-semibold text-primary-foreground mb-1">
                Try our AI Assistant first
              </h3>
              <p className="text-primary-foreground/80 text-sm">
                Get instant answers to common questions. If the AI can&apos;t help, it will create a
                case for you automatically.
              </p>
            </div>
            <Button
              variant="secondary"
              className="w-full sm:w-auto"
              leftIcon={<ChatBubbleLeftRightIcon className="h-5 w-5" />}
            >
              Start Chat
            </Button>
          </div>
        </div>
      </AnimatedCard>

      {/* Error Message */}
      {error && (
        <AlertBanner variant="error" title="Error creating case" elevated>
          {error}
        </AlertBanner>
      )}

      {/* Form */}
      <AnimatedCard variant="static">
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Subject */}
          <div>
            <label
              htmlFor="subject"
              className="block text-sm font-medium text-muted-foreground mb-2"
            >
              Subject <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id="subject"
              value={formData.subject}
              onChange={event => handleInputChange("subject", event.target.value)}
              placeholder="Brief description of your issue"
              className="block w-full px-4 py-3 border border-input rounded-xl text-sm bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring transition-colors"
              maxLength={255}
              required
            />
          </div>

          {/* Priority */}
          <div>
            <label
              htmlFor="priority"
              className="block text-sm font-medium text-muted-foreground mb-2"
            >
              Priority
            </label>
            <select
              id="priority"
              value={formData.priority}
              onChange={event => handleInputChange("priority", event.target.value)}
              className="block w-full sm:w-1/2 px-4 py-3 border border-input rounded-xl text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring transition-colors"
            >
              {priorityOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>

          {/* Description */}
          <div>
            <label
              htmlFor="description"
              className="block text-sm font-medium text-muted-foreground mb-2"
            >
              Description <span className="text-red-500">*</span>
            </label>
            <textarea
              id="description"
              rows={6}
              value={formData.description}
              onChange={event => handleInputChange("description", event.target.value)}
              placeholder="Please provide a detailed description of your issue, including any error messages and steps to reproduce the problem..."
              className="block w-full px-4 py-3 border border-input rounded-xl text-sm bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring transition-colors resize-none"
              required
            />
            <p className="mt-2 text-xs text-muted-foreground">
              The more details you provide, the faster we can help you.
            </p>
          </div>

          {/* Actions */}
          <div className="flex flex-col-reverse sm:flex-row items-center justify-between gap-4 pt-4 border-t border-border">
            <Link
              href="/account/support"
              className="text-sm text-muted-foreground hover:text-foreground font-medium"
            >
              Cancel
            </Link>
            <Button
              type="submit"
              disabled={!isFormValid || createCaseMutation.isPending}
              loading={createCaseMutation.isPending}
              loadingText="Creating Case..."
              leftIcon={<PaperAirplaneIcon className="h-4 w-4" />}
              size="lg"
            >
              Create Case
            </Button>
          </div>
        </form>
      </AnimatedCard>

      {/* Contact Options */}
      <AnimatedCard className="overflow-hidden" variant="static">
        <div className="p-5 border-b border-border">
          <h3 className="text-base font-semibold text-foreground">Need immediate assistance?</h3>
          <p className="text-sm text-muted-foreground mt-1">
            Contact us directly for urgent matters
          </p>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-border">
          {/* Phone Support */}
          <a
            href="tel:0120660470"
            className="group flex items-center gap-4 p-5 hover:bg-muted transition-colors"
          >
            <div className="w-12 h-12 bg-success rounded-xl flex items-center justify-center flex-shrink-0 shadow-[var(--cp-shadow-1)]">
              <svg
                className="h-6 w-6 text-white"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth={1.5}
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z"
                />
              </svg>
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-semibold text-foreground transition-colors">
                Phone Support
              </p>
              <p className="text-2xl font-bold text-foreground mt-0.5">0120-660-470</p>
              <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1.5">
                <span className="w-1.5 h-1.5 bg-success rounded-full"></span>
                Mon-Fri, 9:30-18:00 JST
              </p>
            </div>
          </a>

          {/* AI Chat */}
          <button
            type="button"
            className="group flex items-center gap-4 p-5 hover:bg-muted transition-colors text-left w-full"
          >
            <div className="w-12 h-12 bg-primary rounded-xl flex items-center justify-center flex-shrink-0 shadow-[var(--cp-shadow-1)]">
              <SparklesIcon className="h-6 w-6 text-primary-foreground" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-semibold text-foreground transition-colors">
                AI Chat Assistant
              </p>
              <p className="text-lg font-semibold text-foreground mt-0.5">Get instant answers</p>
              <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1.5">
                <span className="w-1.5 h-1.5 bg-primary rounded-full"></span>
                Available 24/7
              </p>
            </div>
            <div className="flex-shrink-0">
              <span className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-muted text-muted-foreground group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
                <svg
                  className="w-4 h-4"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth={2}
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M8.25 4.5l7.5 7.5-7.5 7.5"
                  />
                </svg>
              </span>
            </div>
          </button>
        </div>
      </AnimatedCard>
    </PageLayout>
  );
}
