'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';

import type { DetailTab } from '@/components/shared/detail-layout';
import { EmptyState } from '@/components/shared/empty-state';
import { InlineEditableField } from '@/components/shared/inline-editable-field';
import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
import { NotesList } from '@/components/shared/notes-list';
import { YachtOwnershipHistory } from '@/components/yachts/yacht-ownership-history';
import { apiFetch } from '@/lib/api/client';

type YachtPatchField =
  | 'name'
  | 'hullNumber'
  | 'registration'
  | 'flag'
  | 'yearBuilt'
  | 'builder'
  | 'model'
  | 'hullMaterial'
  | 'lengthFt'
  | 'widthFt'
  | 'draftFt'
  | 'lengthM'
  | 'widthM'
  | 'draftM'
  | 'status'
  | 'notes';

const STATUS_OPTIONS = [
  { value: 'active', label: 'Active' },
  { value: 'retired', label: 'Retired' },
  { value: 'sold_away', label: 'Sold away' },
];

interface YachtTabsYacht {
  id: string;
  name: string;
  hullNumber: string | null;
  registration: string | null;
  flag: string | null;
  yearBuilt: number | null;
  builder: string | null;
  model: string | null;
  hullMaterial: string | null;
  lengthFt: string | null;
  widthFt: string | null;
  draftFt: string | null;
  lengthM: string | null;
  widthM: string | null;
  draftM: string | null;
  status: string;
  notes: string | null;
  tags?: Array<{ id: string; name: string; color: string }>;
}

interface YachtTabsOptions {
  yachtId: string;
  currentUserId?: string;
  yacht: YachtTabsYacht;
}

function useYachtPatch(yachtId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async (patch: Partial<Record<YachtPatchField, string | number | null>>) =>
      apiFetch(`/api/v1/yachts/${yachtId}`, {
        method: 'PATCH',
        body: patch,
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['yachts', yachtId] });
    },
  });
}

function EditableRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
      <dt className="w-40 shrink-0 text-sm text-muted-foreground">{label}</dt>
      <dd className="flex-1 min-w-0">{children}</dd>
    </div>
  );
}

function OverviewTab({ yachtId, yacht }: { yachtId: string; yacht: YachtTabsYacht }) {
  const mutation = useYachtPatch(yachtId);
  const save =
    (field: YachtPatchField, transform?: (v: string | null) => string | number | null) =>
    async (next: string | null) => {
      const value = transform ? transform(next) : next;
      await mutation.mutateAsync({ [field]: value });
    };
  const numericString = (next: string | null) => (next === null ? null : next);
  const yearTransform = (next: string | null) => {
    if (next === null) return null;
    const n = Number.parseInt(next, 10);
    return Number.isNaN(n) ? null : n;
  };

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      {/* Identity */}
      <div className="space-y-1">
        <h3 className="text-sm font-medium mb-2">Identity</h3>
        <dl>
          <EditableRow label="Name">
            <InlineEditableField value={yacht.name} onSave={save('name')} />
          </EditableRow>
          <EditableRow label="Hull Number">
            <InlineEditableField value={yacht.hullNumber} onSave={save('hullNumber')} />
          </EditableRow>
          <EditableRow label="Registration">
            <InlineEditableField value={yacht.registration} onSave={save('registration')} />
          </EditableRow>
          <EditableRow label="Flag">
            <InlineEditableField value={yacht.flag} onSave={save('flag')} />
          </EditableRow>
          <EditableRow label="Year Built">
            <InlineEditableField
              value={yacht.yearBuilt?.toString() ?? null}
              onSave={save('yearBuilt', yearTransform)}
            />
          </EditableRow>
          <EditableRow label="Status">
            <InlineEditableField
              variant="select"
              options={STATUS_OPTIONS}
              value={yacht.status}
              onSave={save('status')}
            />
          </EditableRow>
        </dl>
      </div>

      {/* Build */}
      <div className="space-y-1">
        <h3 className="text-sm font-medium mb-2">Build</h3>
        <dl>
          <EditableRow label="Builder">
            <InlineEditableField value={yacht.builder} onSave={save('builder')} />
          </EditableRow>
          <EditableRow label="Model">
            <InlineEditableField value={yacht.model} onSave={save('model')} />
          </EditableRow>
          <EditableRow label="Hull Material">
            <InlineEditableField value={yacht.hullMaterial} onSave={save('hullMaterial')} />
          </EditableRow>
        </dl>
      </div>

      {/* Dimensions (ft) */}
      <div className="space-y-1">
        <h3 className="text-sm font-medium mb-2">Dimensions (ft)</h3>
        <dl>
          <EditableRow label="Length (ft)">
            <InlineEditableField value={yacht.lengthFt} onSave={save('lengthFt', numericString)} />
          </EditableRow>
          <EditableRow label="Width (ft)">
            <InlineEditableField value={yacht.widthFt} onSave={save('widthFt', numericString)} />
          </EditableRow>
          <EditableRow label="Draft (ft)">
            <InlineEditableField value={yacht.draftFt} onSave={save('draftFt', numericString)} />
          </EditableRow>
        </dl>
      </div>

      {/* Dimensions (m) */}
      <div className="space-y-1">
        <h3 className="text-sm font-medium mb-2">Dimensions (m)</h3>
        <dl>
          <EditableRow label="Length (m)">
            <InlineEditableField value={yacht.lengthM} onSave={save('lengthM', numericString)} />
          </EditableRow>
          <EditableRow label="Width (m)">
            <InlineEditableField value={yacht.widthM} onSave={save('widthM', numericString)} />
          </EditableRow>
          <EditableRow label="Draft (m)">
            <InlineEditableField value={yacht.draftM} onSave={save('draftM', numericString)} />
          </EditableRow>
        </dl>
      </div>

      {/* Notes */}
      <div className="space-y-1 md:col-span-2">
        <h3 className="text-sm font-medium mb-2">Notes</h3>
        <InlineEditableField
          variant="textarea"
          value={yacht.notes}
          onSave={save('notes')}
          emptyText="No notes — click to add"
        />
      </div>

      {/* Tags */}
      <div className="space-y-1 md:col-span-2">
        <h3 className="text-sm font-medium mb-2">Tags</h3>
        <InlineTagEditor
          endpoint={`/api/v1/yachts/${yachtId}/tags`}
          currentTags={yacht.tags ?? []}
          invalidateKey={['yachts', yachtId]}
        />
      </div>
    </div>
  );
}

export function getYachtTabs({ yachtId, currentUserId, yacht }: YachtTabsOptions): DetailTab[] {
  return [
    {
      id: 'overview',
      label: 'Overview',
      content: <OverviewTab yachtId={yachtId} yacht={yacht} />,
    },
    {
      id: 'ownership-history',
      label: 'Ownership History',
      content: <YachtOwnershipHistory yachtId={yachtId} />,
    },
    {
      id: 'interests',
      label: 'Interests',
      content: <EmptyState title="Interests" description="Coming soon" />,
    },
    {
      id: 'reservations',
      label: 'Reservations',
      content: <EmptyState title="Reservations" description="Coming soon" />,
    },
    {
      id: 'notes',
      label: 'Notes',
      content: <NotesList entityType="yachts" entityId={yachtId} currentUserId={currentUserId} />,
    },
  ];
}
