'use client';

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

export default function VerifyPage(): JSX.Element {
  const apiClient = getApiClient();
  const { success, error: showError } = useToast();
  const [credentialId, setCredentialId] = useState('');
  const [verificationResult, setVerificationResult] = useState<{ valid: boolean; error?: string } | null>(null);

  const mutation = useMutation<Awaited<ReturnType<typeof apiClient.identity.verifyCredential>>, Error, string>({
    mutationFn: async (id: string) => {
      return await apiClient.identity.verifyCredential({
        credential: {
          id,
        },
      });
    },
    onSuccess: (data) => {
      setVerificationResult({ valid: data.valid });
      if (data.valid) {
        success('Credential verified successfully', 'This credential is valid and authentic.');
      } else {
        showError('Credential verification failed', 'This credential could not be verified.');
      }
    },
    onError: (error) => {
      const errorMessage = error instanceof Error ? error.message : 'Verification failed';
      setVerificationResult({
        valid: false,
        error: errorMessage,
      });
      showError(errorMessage, 'Verification Error');
    },
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    if (!credentialId.trim()) {
      setVerificationResult({ valid: false, error: 'Please enter a credential ID' });
      return;
    }
    mutation.mutate(credentialId.trim());
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4 max-w-2xl">
        <Card>
          <CardHeader>
            <CardTitle>Verify Credential</CardTitle>
            <CardDescription>
              Enter a credential ID to verify its validity and authenticity
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <Label htmlFor="credentialId">Credential ID</Label>
                <Input
                  id="credentialId"
                  type="text"
                  placeholder="Enter credential ID"
                  value={credentialId}
                  onChange={(e) => setCredentialId(e.target.value)}
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  The credential ID is typically a UUID or DID identifier
                </p>
              </div>

              {verificationResult && (
                <Alert variant={verificationResult.valid ? 'success' : 'destructive'}>
                  <AlertDescription>
                    {verificationResult.valid ? (
                      <div>
                        <p className="font-semibold">✓ Credential Verified</p>
                        <p className="text-sm mt-1">This credential is valid and authentic.</p>
                      </div>
                    ) : (
                      <div>
                        <p className="font-semibold">✗ Verification Failed</p>
                        <p className="text-sm mt-1">
                          {verificationResult.error || 'The credential could not be verified.'}
                        </p>
                      </div>
                    )}
                  </AlertDescription>
                </Alert>
              )}

              <div className="flex justify-end">
                <Button type="submit" disabled={mutation.isPending}>
                  {mutation.isPending ? 'Verifying...' : 'Verify Credential'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <Card className="mt-6">
          <CardHeader>
            <CardTitle>About Credential Verification</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm text-gray-600">
            <p>
              Credential verification checks the authenticity and validity of verifiable credentials
              issued by The Order.
            </p>
            <p>
              The verification process validates:
            </p>
            <ul className="list-disc list-inside space-y-1 ml-4">
              <li>Credential signature and proof</li>
              <li>Credential expiration status</li>
              <li>Revocation status</li>
              <li>Issuer authenticity</li>
            </ul>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

