'use client';

import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import { formatDistanceToNow } from 'date-fns';
import { toast } from 'sonner';

import { PageHeader } from '@/components/shared/page-header';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

type TriageState = 'open' | 'assigned' | 'converted' | 'dismissed';
type StateFilter = 'inbox' | 'open' | 'assigned' | 'converted' | 'dismissed' | 'all';

interface Submission {
  id: string;
  portId: string;
  submissionId: string;
  kind: 'berth_inquiry' | 'residence_inquiry' | 'contact_form';
  payload: Record<string, unknown> | null;
  legacyNocodbId: string | null;
  sourceIp: string | null;
  userAgent: string | null;
  receivedAt: string;
  triageState: TriageState;
  triagedAt: string | null;
  triagedBy: string | null;
}

const TRIAGE_BADGE: Record<TriageState, string> = {
  open: 'bg-blue-100 text-blue-800',
  assigned: 'bg-amber-100 text-amber-900',
  converted: 'bg-emerald-100 text-emerald-800',
  dismissed: 'bg-slate-100 text-slate-600',
};

interface ListResponse {
  data: Submission[];
  pagination: { nextCursor: { receivedAt: string; id: string } | null };
  counts: Record<string, number>;
}

const KIND_LABELS: Record<Submission['kind'], string> = {
  berth_inquiry: 'Berth inquiry',
  residence_inquiry: 'Residence inquiry',
  contact_form: 'Contact form',
};

const KIND_COLORS: Record<Submission['kind'], string> = {
  berth_inquiry: 'bg-blue-100 text-blue-800',
  residence_inquiry: 'bg-amber-100 text-amber-800',
  contact_form: 'bg-slate-100 text-slate-800',
};

function pickName(payload: Record<string, unknown> | null): string {
  if (!payload) return '';
  const candidates = ['name', 'fullName', 'full_name', 'firstName', 'first_name'];
  for (const k of candidates) {
    const v = payload[k];
    if (typeof v === 'string' && v.trim()) return v.trim();
  }
  return '';
}

function pickEmail(payload: Record<string, unknown> | null): string {
  if (!payload) return '';
  const v = payload['email'];
  return typeof v === 'string' ? v : '';
}

function pickPhone(payload: Record<string, unknown> | null): string {
  if (!payload) return '';
  const v = payload['phone'] ?? payload['phoneNumber'] ?? payload['phone_number'];
  return typeof v === 'string' ? v : '';
}

export function InquiryInbox() {
  const [kind, setKind] = useState<Submission['kind'] | 'all'>('all');
  const [state, setState] = useState<StateFilter>('inbox');
  const [expanded, setExpanded] = useState<string | null>(null);
  const qc = useQueryClient();
  const router = useRouter();
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading, error } = useQuery({
    queryKey: ['inquiry-inbox', kind, state],
    queryFn: () => {
      const qs = new URLSearchParams();
      if (kind !== 'all') qs.set('kind', kind);
      qs.set('state', state);
      return apiFetch<ListResponse>(`/api/v1/admin/website-submissions?${qs}`);
    },
  });

  const counts = data?.counts ?? {};
  const totalAll = useMemo(() => Object.values(counts).reduce((sum, n) => sum + n, 0), [counts]);

  const rows = data?.data ?? [];

  const triageMutation = useMutation({
    mutationFn: (args: { id: string; state: TriageState }) =>
      apiFetch(`/api/v1/admin/website-submissions/${args.id}/triage`, {
        method: 'PATCH',
        body: { state: args.state },
      }),
    onSuccess: (_data, vars) => {
      qc.invalidateQueries({ queryKey: ['inquiry-inbox'] });
      toast.success(`Marked ${vars.state}.`);
    },
    onError: (err: unknown) => {
      toastError(err, 'Triage update failed');
    },
  });

  function convertToClient(row: Submission) {
    // Mark converted then jump to /clients with prefilled query params.
    // The /clients page reads ?prefill_* on mount and opens the New
    // Client form with the values populated. Final form submission is
    // entirely operator-driven; this just hands the data over.
    const name = pickName(row.payload);
    const email = pickEmail(row.payload);
    const phone = pickPhone(row.payload);
    triageMutation.mutate({ id: row.id, state: 'converted' });
    const qs = new URLSearchParams();
    // create=1 auto-opens the new-client sheet; the client-list page
    // reads the prefill_* params and hydrates the form (P-4.5).
    qs.set('create', '1');
    if (name) qs.set('prefill_name', name);
    if (email) qs.set('prefill_email', email);
    if (phone) qs.set('prefill_phone', phone);
    qs.set('prefill_source', 'website');
    qs.set('prefill_inquiry_id', row.id);
    router.push(`/${portSlug}/clients?${qs.toString()}`);
  }

  return (
    <div>
      <PageHeader
        title="Inquiry inbox"
        description="Submissions captured from the public marketing site (berth, residence, and contact forms)."
      />

      <div className="flex items-center gap-2 mt-6 flex-wrap">
        <FilterChip
          label={`All kinds (${totalAll})`}
          active={kind === 'all'}
          onClick={() => setKind('all')}
        />
        <FilterChip
          label={`Berth inquiries (${counts.berth_inquiry ?? 0})`}
          active={kind === 'berth_inquiry'}
          onClick={() => setKind('berth_inquiry')}
        />
        <FilterChip
          label={`Residence (${counts.residence_inquiry ?? 0})`}
          active={kind === 'residence_inquiry'}
          onClick={() => setKind('residence_inquiry')}
        />
        <FilterChip
          label={`Contact (${counts.contact_form ?? 0})`}
          active={kind === 'contact_form'}
          onClick={() => setKind('contact_form')}
        />
      </div>

      <div className="flex items-center gap-2 mt-3 flex-wrap">
        <span className="text-xs text-muted-foreground mr-1">State:</span>
        <FilterChip
          label="Inbox (open + assigned)"
          active={state === 'inbox'}
          onClick={() => setState('inbox')}
        />
        <FilterChip label="Open" active={state === 'open'} onClick={() => setState('open')} />
        <FilterChip
          label="Assigned"
          active={state === 'assigned'}
          onClick={() => setState('assigned')}
        />
        <FilterChip
          label="Converted"
          active={state === 'converted'}
          onClick={() => setState('converted')}
        />
        <FilterChip
          label="Dismissed"
          active={state === 'dismissed'}
          onClick={() => setState('dismissed')}
        />
        <FilterChip label="All states" active={state === 'all'} onClick={() => setState('all')} />
      </div>

      <div className="mt-6">
        {isLoading ? (
          <p className="text-sm text-muted-foreground py-6">Loading…</p>
        ) : error ? (
          <p className="text-sm text-red-600 py-6">
            Failed to load inquiries: {error instanceof Error ? error.message : 'unknown error'}
          </p>
        ) : rows.length === 0 ? (
          <Card>
            <CardContent className="py-10 text-center text-sm text-muted-foreground">
              No website submissions yet for this filter.
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {rows.map((row) => {
              const name = pickName(row.payload);
              const email = pickEmail(row.payload);
              const phone = pickPhone(row.payload);
              const ago = formatDistanceToNow(new Date(row.receivedAt), { addSuffix: true });
              const isOpen = expanded === row.id;
              return (
                <Card key={row.id}>
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 flex-wrap">
                          <Badge className={KIND_COLORS[row.kind]}>{KIND_LABELS[row.kind]}</Badge>
                          <Badge className={TRIAGE_BADGE[row.triageState]}>{row.triageState}</Badge>
                          <span
                            className="text-xs text-muted-foreground"
                            title={new Date(row.receivedAt).toISOString()}
                          >
                            {ago}
                          </span>
                        </div>
                        <CardTitle className="mt-2 text-base font-medium">
                          {name || '(no name supplied)'}
                        </CardTitle>
                        <div className="text-sm text-muted-foreground mt-1 space-x-3">
                          {email ? <span>{email}</span> : null}
                          {phone ? <span>{phone}</span> : null}
                          {row.sourceIp ? (
                            <span className="text-xs">from {row.sourceIp}</span>
                          ) : null}
                        </div>
                      </div>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => setExpanded(isOpen ? null : row.id)}
                      >
                        {isOpen ? 'Hide payload' : 'View payload'}
                      </Button>
                    </div>

                    {row.triageState !== 'converted' && row.triageState !== 'dismissed' && (
                      <div className="mt-3 flex items-center gap-2 flex-wrap">
                        <Button
                          size="sm"
                          onClick={() => convertToClient(row)}
                          disabled={triageMutation.isPending}
                        >
                          Convert to client
                        </Button>
                        {row.triageState === 'open' && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => triageMutation.mutate({ id: row.id, state: 'assigned' })}
                            disabled={triageMutation.isPending}
                          >
                            Assign to me
                          </Button>
                        )}
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => triageMutation.mutate({ id: row.id, state: 'dismissed' })}
                          disabled={triageMutation.isPending}
                        >
                          Dismiss
                        </Button>
                      </div>
                    )}
                    {(row.triageState === 'converted' || row.triageState === 'dismissed') && (
                      <div className="mt-3">
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => triageMutation.mutate({ id: row.id, state: 'open' })}
                          disabled={triageMutation.isPending}
                        >
                          Reopen
                        </Button>
                      </div>
                    )}
                  </CardHeader>
                  {isOpen && (
                    <CardContent>
                      <pre className="bg-muted/40 rounded-md p-3 text-xs overflow-auto max-h-96">
                        {JSON.stringify(row.payload, null, 2)}
                      </pre>
                    </CardContent>
                  )}
                </Card>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function FilterChip({
  label,
  active,
  onClick,
}: {
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`px-3 py-1.5 rounded-full text-sm border transition ${
        active
          ? 'bg-primary text-primary-foreground border-primary'
          : 'bg-background text-foreground border-border hover:bg-muted'
      }`}
    >
      {label}
    </button>
  );
}
