'use client';

import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Eye, EyeOff, Loader2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';

interface AddBerthToInterestDialogProps {
  interestId: string;
  berth: { berthId: string; mooringNumber: string };
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAdded?: () => void;
}

type RoleChoice = 'specific' | 'exploring';

export function AddBerthToInterestDialog({
  interestId,
  berth,
  open,
  onOpenChange,
  onAdded,
}: AddBerthToInterestDialogProps) {
  const queryClient = useQueryClient();
  const [choice, setChoice] = useState<RoleChoice>('specific');

  const mutation = useMutation({
    mutationFn: async (isSpecificInterest: boolean) =>
      apiFetch(`/api/v1/interests/${interestId}/berths`, {
        method: 'POST',
        body: { berthId: berth.berthId, isSpecificInterest },
      }),
    onSuccess: () => {
      // Invalidate the recommender cache + linked-berths cache so both
      // surfaces re-fetch immediately. (See plan §5.3 / §5.5.)
      queryClient.invalidateQueries({ queryKey: ['berth-recommendations', interestId] });
      queryClient.invalidateQueries({ queryKey: ['interest-berths', interestId] });
      queryClient.invalidateQueries({ queryKey: ['interests', interestId] });
      onAdded?.();
      onOpenChange(false);
    },
  });

  const handleSubmit = () => {
    mutation.mutate(choice === 'specific');
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Add berth {berth.mooringNumber} to interest</DialogTitle>
          <DialogDescription>
            Choose how this berth relates to the deal. This drives whether it shows as &ldquo;Under
            Offer&rdquo; on the public map.
          </DialogDescription>
        </DialogHeader>

        <RadioGroup
          value={choice}
          onValueChange={(v) => setChoice(v as RoleChoice)}
          className="gap-3"
        >
          <RoleCard
            value="specific"
            checked={choice === 'specific'}
            title="Pitching specifically"
            description="The client is pitched on this exact berth."
            consequence="This berth will appear as under interest on the public map."
            icon={<Eye className="size-4" aria-hidden />}
          />
          <RoleCard
            value="exploring"
            checked={choice === 'exploring'}
            title="Just exploring"
            description="The berth is being considered or covered by the EOI bundle, but not pitched specifically."
            consequence="This berth stays marked “Available” on the public map - the link is internal only."
            icon={<EyeOff className="size-4" aria-hidden />}
          />
        </RadioGroup>

        {mutation.isError ? (
          <p className="text-sm text-destructive">
            {(mutation.error as Error)?.message ?? 'Failed to add berth.'}
          </p>
        ) : null}

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={mutation.isPending}
          >
            Cancel
          </Button>
          <Button type="button" onClick={handleSubmit} disabled={mutation.isPending}>
            {mutation.isPending ? (
              <Loader2 className="mr-1.5 size-3.5 animate-spin" aria-hidden />
            ) : null}
            Add berth to interest
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

interface RoleCardProps {
  value: RoleChoice;
  checked: boolean;
  title: string;
  description: string;
  consequence: string;
  icon: React.ReactNode;
}

function RoleCard({ value, checked, title, description, consequence, icon }: RoleCardProps) {
  return (
    <Label
      htmlFor={`role-${value}`}
      className={cn(
        'flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors',
        checked ? 'border-brand-300 bg-brand-50/50 ring-1 ring-brand-200' : 'border-border',
      )}
    >
      <RadioGroupItem value={value} id={`role-${value}`} className="mt-1" />
      <div className="flex-1 space-y-1">
        <div className="flex items-center gap-1.5 text-sm font-semibold">
          {icon}
          {title}
        </div>
        <p className="text-xs text-muted-foreground">{description}</p>
        <p className="text-xs font-medium text-foreground/80">{consequence}</p>
      </div>
    </Label>
  );
}
