'use client';

import { useState, useCallback, useEffect } from 'react';
import type { SchemaCheckResult } from '@/lib/types';

interface SchemaCheckTarget {
    subgraph: string;
    parentType: string;
    fieldName: string | null;
}

interface Props {
    target: SchemaCheckTarget;
    onClose: () => void;
}

type ModalState =
    | { step: 'confirm' }
    | { step: 'loading' }
    | { step: 'result'; result: SchemaCheckResult }
    | { step: 'error'; message: string };

export default function SchemaCheckModal({ target, onClose }: Props) {
    const [state, setState] = useState<ModalState>({ step: 'confirm' });

    const label = target.fieldName
        ? `${target.parentType}.${target.fieldName}`
        : target.parentType;

    const runCheck = useCallback(async () => {
        setState({ step: 'loading' });
        try {
            const res = await fetch('/api/schema-check', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(target),
            });
            const data = await res.json();
            if (!res.ok) {
                setState({ step: 'error', message: data.error ?? `HTTP ${res.status}` });
                return;
            }
            setState({ step: 'result', result: data });
        } catch (err) {
            setState({ step: 'error', message: err instanceof Error ? err.message : 'Request failed' });
        }
    }, [target]);

    // Close on Escape
    useEffect(() => {
        const handler = (e: KeyboardEvent) => {
            if (e.key === 'Escape') onClose();
        };
        window.addEventListener('keydown', handler);
        return () => window.removeEventListener('keydown', handler);
    }, [onClose]);

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={onClose}>
            <div
                className="bg-surface border border-border rounded-lg shadow-xl max-w-2xl w-full mx-4"
                onClick={e => e.stopPropagation()}
            >
                <div className="flex items-center justify-between px-5 py-4 border-b border-border">
                    <h2 className="text-sm font-medium text-text-primary">Schema Check</h2>
                    <button onClick={onClose} className="text-text-secondary hover:text-text-primary cursor-pointer">
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <div className="px-5 py-5">
                    {state.step === 'confirm' && (
                        <div>
                            <p className="text-sm text-text-secondary mb-1">
                                Check removal of
                            </p>
                            <p className="text-sm font-mono text-text-primary mb-1">
                                {label}
                            </p>
                            <p className="text-sm text-text-secondary mb-5">
                                from <span className="font-medium text-text-primary">{target.subgraph}</span>
                            </p>
                            <div className="flex justify-end gap-3">
                                <button
                                    onClick={onClose}
                                    className="px-4 py-2 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary cursor-pointer transition-colors"
                                >
                                    Cancel
                                </button>
                                <button
                                    onClick={runCheck}
                                    className="px-4 py-2 text-sm rounded-md bg-accent text-white hover:bg-accent-hover cursor-pointer transition-colors"
                                >
                                    Run Check
                                </button>
                            </div>
                        </div>
                    )}

                    {state.step === 'loading' && (
                        <div className="flex items-center gap-3 py-4">
                            <svg className="w-5 h-5 animate-spin text-accent" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                            </svg>
                            <span className="text-sm text-text-secondary">Running schema check...</span>
                        </div>
                    )}

                    {state.step === 'result' && (
                        <div className="font-mono text-xs leading-relaxed">
                            {/* Header */}
                            <p className="text-text-secondary">
                                Checking the proposed schema for subgraph{' '}
                                <span className="text-accent">{target.subgraph}</span>{' '}
                                against{' '}
                                <span className="text-accent">{state.result.graphRef ?? 'graphql-theorchard@prod'}</span>
                            </p>

                            {/* Operation Check status */}
                            <p className="mt-3 text-text-primary">
                                Operation Check [
                                <span className={state.result.success ? 'text-success' : 'text-danger'}>
                                    {state.result.success ? 'PASSED' : 'FAILED'}
                                </span>
                                ]:
                            </p>
                            <p className="text-text-secondary">
                                Compared {state.result.changes.length} schema change{state.result.changes.length !== 1 ? 's' : ''}{' '}
                                against {state.result.operationCheckCount} operations.
                            </p>

                            {/* Changes table */}
                            {state.result.changes.length > 0 && (
                                <div className="mt-3 max-h-56 overflow-y-auto border border-border rounded">
                                    <table className="w-full text-left">
                                        <thead>
                                            <tr className="border-b border-border bg-surface-hover">
                                                <th className="px-3 py-1.5 text-text-secondary font-medium w-16">Change</th>
                                                <th className="px-3 py-1.5 text-text-secondary font-medium">Code</th>
                                                <th className="px-3 py-1.5 text-text-secondary font-medium">Description</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {state.result.changes.map((change, i) => {
                                                const pass = change.severity !== 'FAILURE';
                                                return (
                                                    <tr key={i} className="border-b border-border/40 last:border-0">
                                                        <td className={`px-3 py-1.5 font-medium ${pass ? 'text-success' : 'text-danger'}`}>
                                                            {pass ? 'PASS' : 'FAIL'}
                                                        </td>
                                                        <td className="px-3 py-1.5 text-text-primary">{change.code}</td>
                                                        <td className="px-3 py-1.5 text-text-secondary">{change.description}</td>
                                                    </tr>
                                                );
                                            })}
                                        </tbody>
                                    </table>
                                </div>
                            )}

                            {/* Studio URL */}
                            {state.result.targetUrl && (
                                <p className="mt-3 text-text-secondary">
                                    View operation check details at:{' '}
                                    <a
                                        href={state.result.targetUrl}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="text-accent hover:text-accent-hover transition-colors break-all"
                                    >
                                        {state.result.targetUrl}
                                    </a>
                                </p>
                            )}

                            {/* File links + close */}
                            <div className="flex items-center justify-between mt-4 pt-3 border-t border-border font-sans text-sm">
                                <div className="flex gap-4">
                                    {state.result.responseFile && (
                                        <a
                                            href={state.result.responseFile}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-text-secondary hover:text-text-primary transition-colors"
                                        >
                                            Raw response
                                        </a>
                                    )}
                                    {state.result.sdlFile && (
                                        <a
                                            href={state.result.sdlFile}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-text-secondary hover:text-text-primary transition-colors"
                                        >
                                            Modified SDL
                                        </a>
                                    )}
                                </div>
                                <button
                                    onClick={onClose}
                                    className="px-4 py-2 rounded-md border border-border text-text-secondary hover:text-text-primary cursor-pointer transition-colors"
                                >
                                    Close
                                </button>
                            </div>
                        </div>
                    )}

                    {state.step === 'error' && (
                        <div>
                            <div className="flex items-start gap-3 mb-4">
                                <svg className="w-5 h-5 text-danger mt-0.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <div>
                                    <p className="text-sm font-medium text-danger">Check failed</p>
                                    <p className="text-sm text-text-secondary mt-1 font-mono break-all">{state.message}</p>
                                </div>
                            </div>
                            <div className="flex justify-end">
                                <button
                                    onClick={onClose}
                                    className="px-4 py-2 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary cursor-pointer transition-colors"
                                >
                                    Close
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
