'use client';

import { useState } from 'react';
import { z } from 'zod';
import { toast } from 'sonner';
import { ArrowRight, Loader2, Lock, Phone, ShieldCheck, User } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';

const paymentSchema = z.object({
  amount: z
    .string()
    .min(1, 'Amount is required')
    .refine((val) => !isNaN(Number(val)) && Number(val) > 0, 'Amount must be a valid positive number')
    .refine((val) => Number(val) >= 10, 'Minimum amount is INR 10')
    .refine((val) => Number(val) <= 100000, 'Maximum amount is INR 1,00,000'),
  customerName: z.string().max(100).optional(),
  customerMobile: z
    .string()
    .regex(/^[0-9]{10}$/, 'Enter a valid 10-digit mobile number')
    .optional()
    .or(z.literal('')),
});

const presets = [100, 500, 1000, 5000];

export default function PaymentPage() {
  const [amount, setAmount] = useState('');
  const [customerName, setCustomerName] = useState('');
  const [customerMobile, setCustomerMobile] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isRedirecting, setIsRedirecting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    const result = paymentSchema.safeParse({
      amount,
      customerName: customerName || undefined,
      customerMobile: customerMobile || undefined,
    });

    if (!result.success) {
      const fieldErrors: Record<string, string> = {};
      for (const issue of result.error.errors) {
        const field = issue.path[0]?.toString() || 'amount';
        fieldErrors[field] = issue.message;
      }
      setErrors(fieldErrors);
      const firstError = Object.values(fieldErrors)[0];
      if (firstError) toast.error(firstError);
      return;
    }

    setIsLoading(true);

    try {
      const payload: { amount: number; customerName?: string; customerMobile?: string } = {
        amount: Number(amount),
      };
      if (customerName.trim()) payload.customerName = customerName.trim();
      if (customerMobile.trim()) payload.customerMobile = customerMobile.trim();

      const response = await fetch('/api/payin/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Failed to create payment order');
      }

      if (!data.paymentUrl) {
        throw new Error('No payment URL received');
      }

      setIsLoading(false);
      setIsRedirecting(true);
      window.location.href = data.paymentUrl;
    } catch (error) {
      setIsLoading(false);
      const message = error instanceof Error ? error.message : 'Something went wrong';
      setErrors({ amount: message });
      toast.error(message);
    }
  };

  const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === '' || /^\d+(\.\d{0,2})?$/.test(value)) {
      setAmount(value);
      if (errors.amount) setErrors((prev) => ({ ...prev, amount: '' }));
    }
  };

  const handleMobileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === '' || /^[0-9]{0,10}$/.test(value)) {
      setCustomerMobile(value);
      if (errors.customerMobile) setErrors((prev) => ({ ...prev, customerMobile: '' }));
    }
  };

  return (
    <main className="min-h-screen bg-black text-white">
      <div className="mx-auto flex min-h-screen w-full max-w-6xl items-center px-4 py-8 sm:px-6 lg:grid lg:grid-cols-[1.1fr_0.9fr] lg:gap-12 lg:px-8">
        <section className="hidden lg:block">
          <div className="max-w-xl">
            <Badge variant="outline" className="mb-6 rounded-full border-white/15 bg-white/5 px-3 py-1 text-[11px] uppercase tracking-[0.22em] text-white/70">
              <ShieldCheck className="h-3.5 w-3.5" />
              Secure payment
            </Badge>

            <h1 className="text-5xl font-semibold tracking-tight text-white">
              Minimal payment page,
              <br />
              built with clarity.
            </h1>

            <p className="mt-5 max-w-md text-base leading-7 text-white/60">
              A clean public checkout with only the essentials, strong contrast, and a familiar shadcn card layout.
            </p>

            <div className="mt-10 space-y-4">
              {[
                ['Fast handoff', 'Create the order and move straight to the payment gateway.'],
                ['Clear input flow', 'Amount first, optional customer details second.'],
                ['Monochrome UI', 'Black and white styling that stays sharp on desktop and mobile.'],
              ].map(([title, description]) => (
                <Card key={title} className="border-white/10 bg-white/[0.03] text-white shadow-none">
                  <CardContent className="p-5">
                    <p className="text-sm font-medium text-white">{title}</p>
                    <p className="mt-2 text-sm leading-6 text-white/55">{description}</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        </section>

        <section className="mx-auto w-full max-w-md">
          <Card className="border-white/10 bg-[#0a0a0a] text-white shadow-2xl shadow-black/50">
            <CardHeader className="space-y-4">
              <div className="flex items-start justify-between gap-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-11 w-11 items-center justify-center rounded-xl border border-white/10 bg-white/5">
                    <Lock className="h-5 w-5 text-white" />
                  </div>
                  <div>
                    <CardTitle className="text-2xl tracking-tight">Pay now</CardTitle>
                    <CardDescription className="mt-1 text-white/55">
                      Simple, direct, and secure.
                    </CardDescription>
                  </div>
                </div>

                <Badge variant="outline" className="border-white/10 bg-transparent text-[10px] uppercase tracking-[0.2em] text-white/45">
                  Live
                </Badge>
              </div>

              <Separator className="bg-white/10" />
            </CardHeader>

            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-5">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="name" className="text-xs uppercase tracking-[0.18em] text-white/45">
                      Name
                    </Label>
                    <div className="relative">
                      <User className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/35" />
                      <Input
                        id="name"
                        type="text"
                        placeholder="Your name"
                        value={customerName}
                        onChange={(e) => setCustomerName(e.target.value)}
                        disabled={isLoading || isRedirecting}
                        className="h-11 border-white/10 bg-white/[0.03] pl-10 text-white placeholder:text-white/25 focus:border-white/30 focus:ring-white/20"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="mobile" className="text-xs uppercase tracking-[0.18em] text-white/45">
                      Mobile
                    </Label>
                    <div className="relative">
                      <Phone className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/35" />
                      <Input
                        id="mobile"
                        type="tel"
                        placeholder="10-digit"
                        maxLength={10}
                        value={customerMobile}
                        onChange={handleMobileChange}
                        disabled={isLoading || isRedirecting}
                        className="h-11 border-white/10 bg-white/[0.03] pl-10 text-white placeholder:text-white/25 focus:border-white/30 focus:ring-white/20"
                      />
                    </div>
                  </div>
                </div>

                {errors.customerMobile && (
                  <p className="-mt-2 text-xs text-white/70">{errors.customerMobile}</p>
                )}

                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="amount" className="text-xs uppercase tracking-[0.18em] text-white/45">
                      Amount
                    </Label>
                    <span className="text-[11px] text-white/35">INR 10 to 1,00,000</span>
                  </div>

                  <div className="rounded-xl border border-white/10 bg-white/[0.03] p-3">
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-medium uppercase tracking-[0.2em] text-white/35">INR</span>
                      <Input
                        id="amount"
                        type="text"
                        inputMode="decimal"
                        placeholder="0.00"
                        value={amount}
                        onChange={handleAmountChange}
                        disabled={isLoading || isRedirecting}
                        autoFocus
                        className="h-auto border-0 bg-transparent p-0 text-4xl font-semibold tracking-tight text-white placeholder:text-white/20 focus-visible:ring-0"
                      />
                    </div>
                  </div>

                  {errors.amount && <p className="text-xs text-white/70">{errors.amount}</p>}
                </div>

                <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                  {presets.map((preset) => (
                    <Button
                      key={preset}
                      type="button"
                      variant="outline"
                      onClick={() => {
                        setAmount(String(preset));
                        setErrors((prev) => ({ ...prev, amount: '' }));
                      }}
                      disabled={isLoading || isRedirecting}
                      className="border-white/10 bg-white/[0.03] text-white/70 hover:bg-white/10 hover:text-white"
                    >
                      {preset.toLocaleString('en-IN')}
                    </Button>
                  ))}
                </div>

                <Button
                  type="submit"
                  disabled={isLoading || isRedirecting || !amount}
                  className="h-12 w-full bg-white text-black hover:bg-white/90 disabled:bg-white/15 disabled:text-white/35"
                >
                  {isLoading ? (
                    <span className="flex items-center gap-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Processing
                    </span>
                  ) : isRedirecting ? (
                    <span className="flex items-center gap-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Redirecting
                    </span>
                  ) : (
                    <span className="flex items-center gap-2">
                      Continue to payment
                      <ArrowRight className="h-4 w-4" />
                    </span>
                  )}
                </Button>
              </form>
            </CardContent>

            <CardFooter className="flex items-center justify-between border-t border-white/10 text-xs uppercase tracking-[0.18em] text-white/35">
              <span>256-bit SSL</span>
              <span>Protected session</span>
            </CardFooter>
          </Card>
        </section>
      </div>

      {isRedirecting && (
        <div className="fixed inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-black/85 backdrop-blur-sm">
          <Loader2 className="h-8 w-8 animate-spin text-white" />
          <p className="text-sm text-white/70">Redirecting to payment...</p>
        </div>
      )}
    </main>
  );
}
