'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetFooter,
} from '@/components/ui/sheet';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { TagPicker } from '@/components/shared/tag-picker';
import { apiFetch } from '@/lib/api/client';
import { updateBerthSchema, type UpdateBerthInput } from '@/lib/validators/berths';

interface BerthFormProps {
  berth: {
    id: string;
    mooringNumber: string;
    area: string | null;
    status: string;
    lengthFt: string | null;
    lengthM: string | null;
    widthFt: string | null;
    widthM: string | null;
    draftFt: string | null;
    draftM: string | null;
    widthIsMinimum: boolean | null;
    price: string | null;
    priceCurrency: string;
    tenureType: string;
    tenureYears: number | null;
    tenureStartDate: string | null;
    tenureEndDate: string | null;
    powerCapacity: string | null;
    voltage: string | null;
    mooringType: string | null;
    access: string | null;
    berthApproved: boolean | null;
    tags: Array<{ id: string; name: string; color: string }>;
  };
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function BerthForm({ berth, open, onOpenChange }: BerthFormProps) {
  const queryClient = useQueryClient();
  const [tagIds, setTagIds] = useState<string[]>(berth.tags.map((t) => t.id));

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { isSubmitting },
  } = useForm<UpdateBerthInput>({
    resolver: zodResolver(updateBerthSchema),
    defaultValues: {
      area: berth.area ?? undefined,
      lengthFt: berth.lengthFt ? Number(berth.lengthFt) : undefined,
      lengthM: berth.lengthM ? Number(berth.lengthM) : undefined,
      widthFt: berth.widthFt ? Number(berth.widthFt) : undefined,
      widthM: berth.widthM ? Number(berth.widthM) : undefined,
      draftFt: berth.draftFt ? Number(berth.draftFt) : undefined,
      draftM: berth.draftM ? Number(berth.draftM) : undefined,
      widthIsMinimum: berth.widthIsMinimum ?? false,
      price: berth.price ? Number(berth.price) : undefined,
      priceCurrency: berth.priceCurrency,
      tenureType: berth.tenureType as 'permanent' | 'fixed_term',
      tenureYears: berth.tenureYears ?? undefined,
      tenureStartDate: berth.tenureStartDate ?? undefined,
      tenureEndDate: berth.tenureEndDate ?? undefined,
      powerCapacity: berth.powerCapacity ?? undefined,
      voltage: berth.voltage ?? undefined,
      mooringType: berth.mooringType ?? undefined,
      access: berth.access ?? undefined,
      berthApproved: berth.berthApproved ?? false,
    },
  });

  const tagMutation = useMutation({
    mutationFn: (ids: string[]) =>
      apiFetch(`/api/v1/berths/${berth.id}/tags`, {
        method: 'PUT',
        body: { tagIds: ids },
      }),
  });

  async function onSubmit(data: UpdateBerthInput) {
    try {
      await apiFetch(`/api/v1/berths/${berth.id}`, {
        method: 'PATCH',
        body: data,
      });
      await tagMutation.mutateAsync(tagIds);
      queryClient.invalidateQueries({ queryKey: ['berths'] });
      queryClient.invalidateQueries({ queryKey: ['berth', berth.id] });
      toast.success('Berth updated');
      onOpenChange(false);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Failed to update berth';
      toast.error(message);
    }
  }

  const tenureType = watch('tenureType');

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-[480px] sm:w-[540px] overflow-y-auto">
        <SheetHeader>
          <SheetTitle>Edit Berth {berth.mooringNumber}</SheetTitle>
        </SheetHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 py-6">
          {/* Basic Info */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Basic Info
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="area">Area</Label>
                <Input id="area" {...register('area')} placeholder="e.g. Marina A" />
              </div>
              <div className="space-y-2">
                <Label htmlFor="mooringType">Mooring Type</Label>
                <Input id="mooringType" {...register('mooringType')} />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="access">Access</Label>
              <Input id="access" {...register('access')} />
            </div>
            <div className="flex items-center gap-2">
              <Switch
                id="berthApproved"
                checked={watch('berthApproved') ?? false}
                onCheckedChange={(v) => setValue('berthApproved', v)}
              />
              <Label htmlFor="berthApproved">Berth Approved</Label>
            </div>
          </div>

          <Separator />

          {/* Dimensions */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Dimensions
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Length (ft)</Label>
                <Input type="number" step="0.1" {...register('lengthFt')} />
              </div>
              <div className="space-y-2">
                <Label>Length (m)</Label>
                <Input type="number" step="0.1" {...register('lengthM')} />
              </div>
              <div className="space-y-2">
                <Label>Width (ft)</Label>
                <Input type="number" step="0.1" {...register('widthFt')} />
              </div>
              <div className="space-y-2">
                <Label>Width (m)</Label>
                <Input type="number" step="0.1" {...register('widthM')} />
              </div>
              <div className="space-y-2">
                <Label>Draft (ft)</Label>
                <Input type="number" step="0.1" {...register('draftFt')} />
              </div>
              <div className="space-y-2">
                <Label>Draft (m)</Label>
                <Input type="number" step="0.1" {...register('draftM')} />
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                id="widthIsMinimum"
                checked={watch('widthIsMinimum') ?? false}
                onCheckedChange={(v) => setValue('widthIsMinimum', v)}
              />
              <Label htmlFor="widthIsMinimum">Width is minimum</Label>
            </div>
          </div>

          <Separator />

          {/* Price */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Price
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Price</Label>
                <Input type="number" step="0.01" {...register('price')} />
              </div>
              <div className="space-y-2">
                <Label>Currency</Label>
                <Input {...register('priceCurrency')} placeholder="USD" maxLength={3} />
              </div>
            </div>
          </div>

          <Separator />

          {/* Tenure */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Tenure
            </h3>
            <div className="space-y-2">
              <Label>Tenure Type</Label>
              <Select
                value={tenureType}
                onValueChange={(v) => setValue('tenureType', v as 'permanent' | 'fixed_term')}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="permanent">Permanent</SelectItem>
                  <SelectItem value="fixed_term">Fixed Term</SelectItem>
                </SelectContent>
              </Select>
            </div>
            {tenureType === 'fixed_term' && (
              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label>Years</Label>
                  <Input type="number" {...register('tenureYears')} />
                </div>
                <div className="space-y-2">
                  <Label>Start Date</Label>
                  <Input type="date" {...register('tenureStartDate')} />
                </div>
                <div className="space-y-2">
                  <Label>End Date</Label>
                  <Input type="date" {...register('tenureEndDate')} />
                </div>
              </div>
            )}
          </div>

          <Separator />

          {/* Infrastructure */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Infrastructure
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Power Capacity</Label>
                <Input {...register('powerCapacity')} />
              </div>
              <div className="space-y-2">
                <Label>Voltage</Label>
                <Input {...register('voltage')} />
              </div>
            </div>
          </div>

          <Separator />

          {/* Tags */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Tags
            </h3>
            <TagPicker selectedIds={tagIds} onChange={setTagIds} />
          </div>

          <SheetFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? 'Saving...' : 'Save Changes'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
