'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label, Button } from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';
import { useToast } from '@the-order/ui';

export default function ApplyPage(): JSX.Element {
  const router = useRouter();
  const apiClient = getApiClient();
  const { success, error: showError } = useToast();
  const [formData, setFormData] = useState({
    email: '',
    givenName: '',
    familyName: '',
    dateOfBirth: '',
    nationality: '',
    phone: '',
    street: '',
    city: '',
    region: '',
    postalCode: '',
    country: '',
  });

  const mutation = useMutation<Awaited<ReturnType<typeof apiClient.eresidency.submitApplication>>, Error, typeof formData>({
    mutationFn: async (data: typeof formData) => {
      return await apiClient.eresidency.submitApplication({
        email: data.email,
        givenName: data.givenName,
        familyName: data.familyName,
        dateOfBirth: data.dateOfBirth || undefined,
        nationality: data.nationality || undefined,
        phone: data.phone || undefined,
        address: data.street || data.city || data.region || data.postalCode || data.country
          ? {
              street: data.street || undefined,
              city: data.city || undefined,
              region: data.region || undefined,
              postalCode: data.postalCode || undefined,
              country: data.country || undefined,
            }
          : undefined,
      });
    },
    onSuccess: (data) => {
      success('Application submitted successfully!', 'Your eResidency application has been received.');
      router.push(`/status?id=${data.id}`);
    },
    onError: (error) => {
      showError(
        error instanceof Error ? error.message : 'Failed to submit application',
        'Submission Error'
      );
    },
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    mutation.mutate(formData);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4 max-w-2xl">
        <Card>
          <CardHeader>
            <CardTitle>Apply for eResidency</CardTitle>
            <CardDescription>
              Complete the form below to apply for eResidency with The Order
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="space-y-4">
                <div>
                  <Label htmlFor="email">Email Address *</Label>
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    required
                    value={formData.email}
                    onChange={handleChange}
                    placeholder="your.email@example.com"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="givenName">Given Name *</Label>
                    <Input
                      id="givenName"
                      name="givenName"
                      required
                      value={formData.givenName}
                      onChange={handleChange}
                      placeholder="John"
                    />
                  </div>
                  <div>
                    <Label htmlFor="familyName">Family Name *</Label>
                    <Input
                      id="familyName"
                      name="familyName"
                      required
                      value={formData.familyName}
                      onChange={handleChange}
                      placeholder="Doe"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="dateOfBirth">Date of Birth</Label>
                    <Input
                      id="dateOfBirth"
                      name="dateOfBirth"
                      type="date"
                      value={formData.dateOfBirth}
                      onChange={handleChange}
                    />
                  </div>
                  <div>
                    <Label htmlFor="nationality">Nationality</Label>
                    <Input
                      id="nationality"
                      name="nationality"
                      value={formData.nationality}
                      onChange={handleChange}
                      placeholder="US"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="phone">Phone Number</Label>
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={handleChange}
                    placeholder="+1 (555) 123-4567"
                  />
                </div>

                <div className="border-t pt-4">
                  <h3 className="text-lg font-semibold mb-4">Address (Optional)</h3>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="street">Street Address</Label>
                      <Input
                        id="street"
                        name="street"
                        value={formData.street}
                        onChange={handleChange}
                        placeholder="123 Main St"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="city">City</Label>
                        <Input
                          id="city"
                          name="city"
                          value={formData.city}
                          onChange={handleChange}
                          placeholder="New York"
                        />
                      </div>
                      <div>
                        <Label htmlFor="region">Region/State</Label>
                        <Input
                          id="region"
                          name="region"
                          value={formData.region}
                          onChange={handleChange}
                          placeholder="NY"
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="postalCode">Postal Code</Label>
                        <Input
                          id="postalCode"
                          name="postalCode"
                          value={formData.postalCode}
                          onChange={handleChange}
                          placeholder="10001"
                        />
                      </div>
                      <div>
                        <Label htmlFor="country">Country</Label>
                        <Input
                          id="country"
                          name="country"
                          value={formData.country}
                          onChange={handleChange}
                          placeholder="United States"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>


              <div className="flex justify-end gap-4">
                <Button type="button" variant="secondary" onClick={() => router.back()}>
                  Cancel
                </Button>
                <Button type="submit" disabled={mutation.isPending}>
                  {mutation.isPending ? 'Submitting...' : 'Submit Application'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

