'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';

import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { PageHeader } from '@/components/shared/page-header';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import { PIPELINE_STAGES } from '@/lib/validators/residential';

interface ResidentialInterestRow {
  id: string;
  residentialClientId: string;
  pipelineStage: string;
  source: string | null;
  notes: string | null;
  preferences: string | null;
  assignedTo: string | null;
  updatedAt: string;
}

interface ListResponse {
  data: ResidentialInterestRow[];
  pagination: { total: number };
}

const STAGE_LABELS: Record<string, string> = {
  new: 'New',
  contacted: 'Contacted',
  viewing_scheduled: 'Viewing scheduled',
  offer_made: 'Offer made',
  offer_accepted: 'Offer accepted',
  closed_won: 'Closed - won',
  closed_lost: 'Closed - lost',
};

export function ResidentialInterestsList() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const [search, setSearch] = useState('');
  const [stage, setStage] = useState<string>('all');

  const { data, isLoading } = useQuery<ListResponse>({
    queryKey: ['residential-interests', { search, stage }],
    queryFn: () => {
      const qs = new URLSearchParams({ search, limit: '50' });
      if (stage !== 'all') qs.set('pipelineStage', stage);
      return apiFetch(`/api/v1/residential/interests?${qs.toString()}`);
    },
  });

  useRealtimeInvalidation({
    'residential_interest:created': [['residential-interests']],
    'residential_interest:updated': [['residential-interests']],
    'residential_interest:archived': [['residential-interests']],
  });

  return (
    <div className="space-y-4">
      <PageHeader
        title="Residential Interests"
        description="Inquiries flowing through the residential pipeline"
      />

      <div className="flex items-center gap-2">
        <Input
          placeholder="Search notes / preferences…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="max-w-sm h-9"
        />
        <Select value={stage} onValueChange={setStage}>
          <SelectTrigger className="w-52">
            <SelectValue placeholder="All stages" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All stages</SelectItem>
            {PIPELINE_STAGES.map((s) => (
              <SelectItem key={s} value={s}>
                {STAGE_LABELS[s] ?? s}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Desktop: table layout. Hidden below lg; mobile renders cards. */}
      <div className="hidden lg:block rounded-lg border bg-card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-muted/40 text-xs text-muted-foreground">
            <tr>
              <th className="text-left font-medium px-3 py-2">Stage</th>
              <th className="text-left font-medium px-3 py-2">Preferences</th>
              <th className="text-left font-medium px-3 py-2">Notes</th>
              <th className="text-left font-medium px-3 py-2">Source</th>
              <th className="text-left font-medium px-3 py-2">Updated</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td colSpan={5} className="px-3 py-8 text-center text-muted-foreground">
                  Loading…
                </td>
              </tr>
            )}
            {!isLoading && data?.data.length === 0 && (
              <tr>
                <td colSpan={5} className="px-3 py-8 text-center text-muted-foreground">
                  No interests match.
                </td>
              </tr>
            )}
            {data?.data.map((i) => (
              <tr
                key={i.id}
                className="border-t hover:bg-muted/30 transition-colors cursor-pointer"
              >
                <td className="px-3 py-2">
                  <Link
                    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
                    href={`/${portSlug}/residential/interests/${i.id}` as any}
                    className="font-medium hover:underline"
                  >
                    {STAGE_LABELS[i.pipelineStage] ?? i.pipelineStage}
                  </Link>
                </td>
                <td className="px-3 py-2 text-muted-foreground truncate max-w-xs">
                  {i.preferences ?? '-'}
                </td>
                <td className="px-3 py-2 text-muted-foreground truncate max-w-xs">
                  {i.notes ?? '-'}
                </td>
                <td className="px-3 py-2 capitalize text-muted-foreground">{i.source ?? '-'}</td>
                <td className="px-3 py-2 text-muted-foreground text-xs">
                  {new Date(i.updatedAt).toLocaleDateString()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Mobile: card list. Stage as the headline (it's the most actionable
          field for triage), preferences/notes truncated below. */}
      <div className="lg:hidden space-y-2">
        {isLoading && (
          <div className="rounded-lg border bg-card px-3 py-8 text-center text-sm text-muted-foreground">
            Loading…
          </div>
        )}
        {!isLoading && data?.data.length === 0 && (
          <div className="rounded-lg border bg-card px-3 py-8 text-center text-sm text-muted-foreground">
            No interests match.
          </div>
        )}
        {data?.data.map((i) => (
          <Link
            key={i.id}
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            href={`/${portSlug}/residential/interests/${i.id}` as any}
            className="block rounded-lg border bg-card p-3 transition-colors hover:bg-muted/30"
          >
            <div className="flex items-start justify-between gap-2">
              <p className="font-medium text-sm">
                {STAGE_LABELS[i.pipelineStage] ?? i.pipelineStage}
              </p>
              <span className="shrink-0 text-[11px] text-muted-foreground">
                {new Date(i.updatedAt).toLocaleDateString()}
              </span>
            </div>
            {i.preferences ? (
              <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{i.preferences}</p>
            ) : null}
            {i.notes ? (
              <p className="mt-1 line-clamp-1 text-xs text-muted-foreground/80">{i.notes}</p>
            ) : null}
            {i.source ? (
              <p className="mt-1 text-[11px] capitalize text-muted-foreground">{i.source}</p>
            ) : null}
          </Link>
        ))}
      </div>
    </div>
  );
}
