'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,
  Select,
  Textarea,
  useToast,
  Alert,
  AlertDescription,
} from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';

export default function IssueCredentialPage(): JSX.Element {
  const router = useRouter();
  const apiClient = getApiClient();
  const { success, error: showError } = useToast();
  const [formData, setFormData] = useState({
    subjectDid: '',
    credentialType: 'eResident' as 'eResident' | 'eCitizen',
    expirationDate: '',
    givenName: '',
    familyName: '',
    email: '',
    dateOfBirth: '',
    nationality: '',
    notes: '',
  });

  const mutation = useMutation<Awaited<ReturnType<typeof apiClient.identity.issueCredential>>, Error, typeof formData>({
    mutationFn: async (data: typeof formData) => {
      const credentialSubject: Record<string, unknown> = {
        givenName: data.givenName,
        familyName: data.familyName,
        email: data.email,
      };

      if (data.dateOfBirth) {
        credentialSubject.dateOfBirth = data.dateOfBirth;
      }
      if (data.nationality) {
        credentialSubject.nationality = data.nationality;
      }

      return await apiClient.identity.issueCredential({
        subject: data.subjectDid,
        credentialSubject,
        expirationDate: data.expirationDate || undefined,
      });
    },
    onSuccess: (data) => {
      success('Credential issued successfully', `Credential ID: ${data.credential.id}`);
      router.push('/credentials');
    },
    onError: (error) => {
      showError(
        error instanceof Error ? error.message : 'Failed to issue credential',
        'Issuance Error'
      );
    },
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    if (!formData.subjectDid.trim()) {
      showError('Subject DID is required', 'Validation Error');
      return;
    }
    if (!formData.givenName.trim() || !formData.familyName.trim()) {
      showError('Given name and family name are required', 'Validation Error');
      return;
    }
    mutation.mutate(formData);
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4 max-w-3xl">
        <div className="mb-6">
          <Button variant="outline" onClick={() => router.push('/credentials')}>
            ← Back to Credentials
          </Button>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Issue New Credential</CardTitle>
            <CardDescription>
              Create and issue a new verifiable credential to a subject
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <Label htmlFor="subjectDid">Subject DID *</Label>
                <Input
                  id="subjectDid"
                  required
                  value={formData.subjectDid}
                  onChange={(e) => setFormData({ ...formData, subjectDid: e.target.value })}
                  placeholder="did:example:123456789"
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  The Decentralized Identifier (DID) of the credential subject
                </p>
              </div>

              <div>
                <Label htmlFor="credentialType">Credential Type *</Label>
                <Select
                  id="credentialType"
                  required
                  value={formData.credentialType}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      credentialType: e.target.value as 'eResident' | 'eCitizen',
                    })
                  }
                  className="mt-2"
                >
                  <option value="eResident">eResident</option>
                  <option value="eCitizen">eCitizen</option>
                </Select>
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="givenName">Given Name *</Label>
                  <Input
                    id="givenName"
                    required
                    value={formData.givenName}
                    onChange={(e) => setFormData({ ...formData, givenName: e.target.value })}
                    className="mt-2"
                  />
                </div>
                <div>
                  <Label htmlFor="familyName">Family Name *</Label>
                  <Input
                    id="familyName"
                    required
                    value={formData.familyName}
                    onChange={(e) => setFormData({ ...formData, familyName: e.target.value })}
                    className="mt-2"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="mt-2"
                />
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="dateOfBirth">Date of Birth</Label>
                  <Input
                    id="dateOfBirth"
                    type="date"
                    value={formData.dateOfBirth}
                    onChange={(e) => setFormData({ ...formData, dateOfBirth: e.target.value })}
                    className="mt-2"
                  />
                </div>
                <div>
                  <Label htmlFor="nationality">Nationality</Label>
                  <Input
                    id="nationality"
                    value={formData.nationality}
                    onChange={(e) => setFormData({ ...formData, nationality: e.target.value })}
                    className="mt-2"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="expirationDate">Expiration Date</Label>
                <Input
                  id="expirationDate"
                  type="date"
                  value={formData.expirationDate}
                  onChange={(e) => setFormData({ ...formData, expirationDate: e.target.value })}
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  Leave empty for credentials that don't expire
                </p>
              </div>

              <div>
                <Label htmlFor="notes">Notes (Internal)</Label>
                <Textarea
                  id="notes"
                  rows={3}
                  value={formData.notes}
                  onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                  className="mt-2"
                  placeholder="Internal notes about this credential issuance..."
                />
              </div>

              {mutation.isError && (
                <Alert variant="destructive">
                  <AlertDescription>
                    {mutation.error instanceof Error
                      ? mutation.error.message
                      : 'An error occurred while issuing the credential'}
                  </AlertDescription>
                </Alert>
              )}

              <div className="flex justify-end gap-4">
                <Button variant="outline" type="button" onClick={() => router.push('/credentials')}>
                  Cancel
                </Button>
                <Button type="submit" disabled={mutation.isPending}>
                  {mutation.isPending ? 'Issuing...' : 'Issue Credential'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

