'use client';

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

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PermissionGate } from '@/components/shared/permission-gate';
import { EmptyState } from '@/components/shared/empty-state';
import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { BerthReserveDialog } from '@/components/tenancies/berth-reserve-dialog';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';

interface BerthTenanciesTabProps {
  berthId: string;
}

export function BerthTenanciesTab({ berthId }: BerthTenanciesTabProps) {
  const routeParams = useParams<{ portSlug: string }>();
  const portSlug = routeParams?.portSlug ?? '';
  const [reserveOpen, setReserveOpen] = useState(false);

  const { data, isLoading } = useQuery<{ data: TenancyRow[]; pagination?: unknown }>({
    queryKey: ['berths', berthId, 'tenancies'],
    queryFn: () =>
      apiFetch(
        `/api/v1/berths/${berthId}/tenancies?page=1&limit=50&order=desc&includeArchived=false`,
      ),
  });

  useRealtimeInvalidation({
    'berth_tenancy:created': [['berths', berthId, 'tenancies']],
    'berth_tenancy:activated': [['berths', berthId, 'tenancies']],
    'berth_tenancy:updated': [['berths', berthId, 'tenancies']],
    'berth_tenancy:ended': [['berths', berthId, 'tenancies']],
    'berth_tenancy:cancelled': [['berths', berthId, 'tenancies']],
  });

  const tenancies = data?.data ?? [];
  const active = tenancies.find((r) => r.status === 'active');
  const history = tenancies.filter((r) => r.status !== 'active');

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">Tenancies</h3>
        <PermissionGate resource="tenancies" action="manage">
          <Button size="sm" onClick={() => setReserveOpen(true)}>
            <Plus className="mr-1.5 h-4 w-4" aria-hidden />
            Create tenancy
          </Button>
        </PermissionGate>
      </div>

      {/* Active tenancy card */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-medium">Active tenancy</CardTitle>
        </CardHeader>
        <CardContent>
          {active ? (
            <TenancyList tenancies={[active]} portSlug={portSlug} />
          ) : (
            <p className="text-sm text-muted-foreground">No active tenancy.</p>
          )}
        </CardContent>
      </Card>

      {/* History */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-medium">History</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : history.length === 0 ? (
            <EmptyState title="No past tenancies" description="Nothing here yet." />
          ) : (
            <TenancyList tenancies={history} portSlug={portSlug} />
          )}
        </CardContent>
      </Card>

      <BerthReserveDialog open={reserveOpen} onOpenChange={setReserveOpen} berthId={berthId} />
    </div>
  );
}
