'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"
        />
        <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>

      <div className="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>
    </div>
  );
}
