'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download, Eye, ShieldCheck, ShieldOff } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import { verifaydaApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

const Field = ({ label, value, mono = false, truncate = false }: { label: string; value: string; mono?: boolean; truncate?: boolean }) => (
  <div className="bg-muted/40 rounded-lg p-3">
    <p className="text-xs text-muted-foreground mb-1">{label}</p>
    <p className={`text-sm font-semibold text-foreground${mono ? ' font-mono' : ''}${truncate ? ' truncate' : ''}`} title={value}>{value || '—'}</p>
  </div>
);

const SectionHeader = ({ title }: { title: string }) => (
  <h3 className="text-xs font-bold uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2">
    <span className="w-4 h-px bg-muted-foreground/40 inline-block" />{title}
  </h3>
);

export default function VerifaydaPage() {
  const [filters, setFilters] = useState({ search: '', verified: '' });
  const [selected, setSelected] = useState<any>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['verifayda', filters],
    queryFn: () => verifaydaApi.getVerifications(filters),
  });

  const columns = [
    { key: 'nationalId', label: 'National ID', render: (ver: any) => <span className="font-mono">{ver.nationalId}</span> },
    { key: 'fullName', label: 'Name', render: (ver: any) => ver.fullName || ver.returnedName || 'N/A' },
    { key: 'verified', label: 'Status', render: (ver: any) => (
      <Badge variant="status" status={ver.verified ? 'CONFIRMED' : 'CANCELLED'}>
        {ver.verified ? 'Verified' : 'Failed'}
      </Badge>
    )},
    { key: 'createdAt', label: 'Verified At', render: (ver: any) => formatDateTime(ver.createdAt) },
  ];

  const actions = [
    { label: 'View Details', onClick: (v: any) => setSelected(v), variant: 'secondary' as const, icon: Eye },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Verifayda Integration</h1>
          <p className="text-muted-foreground">Ethiopian national ID verification logs</p>
        </div>
        <ActionButton icon={Download} variant="secondary">Export</ActionButton>
      </div>

      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search</label>
            <input type="text" placeholder="Search by National ID..." className="input" value={filters.search} onChange={(e) => setFilters({ ...filters, search: e.target.value })} />
          </div>
          <div>
            <label className="label">Status</label>
            <select className="input" value={filters.verified} onChange={(e) => setFilters({ ...filters, verified: e.target.value })}>
              <option value="">All</option>
              <option value="true">Verified</option>
              <option value="false">Failed</option>
            </select>
          </div>
        </div>
      </div>

      <DataTable
        data={data?.items || data || []}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No verification records found"
      />

      {/* Verifayda Details Modal */}
      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Verification Details" size="xl">
        {selected && (() => {
          const v = selected;
          const isVerified = !!v.verified;
          const grad = isVerified ? 'from-emerald-600 to-emerald-700' : 'from-red-600 to-red-700';
          const name = v.fullName || v.returnedName || 'N/A';
          return (
            <div>
              <div className={`-mx-6 -mt-4 mb-6 px-6 py-5 bg-gradient-to-r ${grad} rounded-t-lg`}>
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-full bg-white/20 flex items-center justify-center shrink-0">
                    {isVerified
                      ? <ShieldCheck className="w-7 h-7 text-white" />
                      : <ShieldOff className="w-7 h-7 text-white" />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-white text-xl font-bold truncate">{name}</p>
                    <p className="text-white/70 text-sm font-mono">{v.nationalId}</p>
                  </div>
                  <div className="text-right shrink-0">
                    <Badge variant="status" status={isVerified ? 'CONFIRMED' : 'CANCELLED'}>
                      {isVerified ? '✓ Verified' : '✗ Failed'}
                    </Badge>
                    <p className="text-white/70 text-xs mt-1">{formatDateTime(v.createdAt)}</p>
                  </div>
                </div>
                <div className="mt-4 grid grid-cols-3 gap-3">
                  {[
                    { label: 'National ID', value: v.nationalId || '—' },
                    { label: 'Date of Birth', value: v.dateOfBirth || v.returnedDob || '—' },
                    { label: 'Nationality', value: v.nationality || 'Ethiopian' },
                  ].map(({ label, value }) => (
                    <div key={label} className="bg-white/10 rounded-lg px-3 py-2">
                      <p className="text-white/70 text-xs">{label}</p>
                      <p className="text-white text-sm font-bold truncate">{value}</p>
                    </div>
                  ))}
                </div>
              </div>

              <div className="space-y-6">
                <section>
                  <SectionHeader title="Verification Result" />
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <div className="bg-muted/40 rounded-lg p-3">
                      <p className="text-xs text-muted-foreground mb-2">Status</p>
                      <div className="flex items-center gap-2">
                        {isVerified
                          ? <ShieldCheck className="w-4 h-4 text-emerald-600 shrink-0" />
                          : <ShieldOff className="w-4 h-4 text-red-500 shrink-0" />}
                        <span className={`text-sm font-semibold ${isVerified ? 'text-emerald-700 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
                          {isVerified ? 'Verified' : 'Failed'}
                        </span>
                      </div>
                    </div>
                    <Field label="Verified At" value={formatDateTime(v.createdAt)} />
                    <Field label="Failure Reason" value={v.failureReason || (isVerified ? 'N/A' : 'Verification failed')} truncate />
                    <Field label="Response Code" value={v.responseCode || 'N/A'} mono />
                  </div>
                </section>

                <section>
                  <SectionHeader title="Identity Data (from Fayda)" />
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <Field label="National ID" value={v.nationalId} mono />
                    <Field label="Full Name" value={v.fullName || v.returnedName} />
                    <Field label="Date of Birth" value={v.dateOfBirth || v.returnedDob} />
                    <Field label="Gender" value={v.gender || v.returnedGender} />
                    <Field label="Nationality" value={v.nationality || 'Ethiopian'} />
                    <Field label="Phone" value={v.phone || v.returnedPhone} />
                  </div>
                </section>

                <section>
                  <SectionHeader title="Linked Passenger" />
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    <Field label="Passenger Name" value={v.passenger?.fullName || v.user?.fullName} />
                    <Field label="Email" value={v.passenger?.email || v.user?.email} truncate />
                    <Field label="Passenger ID" value={v.passengerId || v.passenger?.id} mono truncate />
                  </div>
                </section>

                <section>
                  <SectionHeader title="System" />
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    <Field label="Record ID" value={v.id} mono truncate />
                    <Field label="Created" value={formatDateTime(v.createdAt)} />
                    <Field label="Last Updated" value={formatDateTime(v.updatedAt)} />
                  </div>
                </section>
              </div>

              <div className="flex justify-end gap-2 pt-6 mt-2 border-t border-muted">
                <ActionButton variant="secondary" onClick={() => setSelected(null)}>Close</ActionButton>
              </div>
            </div>
          );
        })()}
      </Modal>
    </div>
  );
}
