import { useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckCircle, HelpCircle, Monitor, Smartphone, Tablet } from 'lucide-react';

import { UserService } from '@/client/services/UserService';
import { useDevices } from '@/hooks/user/useDevices';

import { SectionHeading } from './primitives';

function deviceIcon(type: string | null | undefined) {
  const t = (type ?? '').toLowerCase();
  if (t.includes('mobile') || t.includes('phone'))
    return <Smartphone className="size-5 shrink-0 text-muted-foreground" />;
  if (t.includes('tablet') || t.includes('ipad'))
    return <Tablet className="size-5 shrink-0 text-muted-foreground" />;
  return <Monitor className="size-5 shrink-0 text-muted-foreground" />;
}

export function DevicesTab() {
  const { data: devices, isLoading, error } = useDevices();
  const queryClient = useQueryClient();

  const deleteMutation = useMutation({
    mutationFn: (deviceId: string) => UserService.userDeleteDevice({ deviceId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'devices'] });
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load devices.
        </div>
      </div>
    );
  }

  return (
    <div className="px-8 pt-10 pb-8 max-w-[640px]">
      <SectionHeading
        title="Devices"
        description="Manage trusted devices used for two-factor authentication and session verification."
      />

      {(devices ?? []).length === 0 ? (
        <div className="rounded-lg border border-dashed border-border px-4 py-10 text-center">
          <Monitor className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No devices registered.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {(devices ?? []).map((device) => (
            <div
              key={device.id}
              className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 transition-colors hover:bg-muted"
            >
              {deviceIcon(device.device_type)}
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <p className="text-[14px] font-medium text-foreground">{device.device_name}</p>
                  <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
                    {device.device_type}
                  </span>
                  {device.trusted ? (
                    <span className="shrink-0 inline-flex items-center gap-1 rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-medium text-primary">
                      <CheckCircle className="size-3" />
                      Trusted
                    </span>
                  ) : (
                    <span className="shrink-0 inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[11px] font-medium text-amber-600">
                      <HelpCircle className="size-3" />
                      Unverified
                    </span>
                  )}
                </div>
                <p className="mt-0.5 flex items-center gap-2 text-[12px] text-muted-foreground">
                  {device.ip_address && <span>{device.ip_address}</span>}
                  {device.user_agent && (
                    <>
                      <span className="text-border">·</span>
                      <span className="truncate">{device.user_agent}</span>
                    </>
                  )}
                </p>
                {device.last_seen_at && (
                  <p className="mt-0.5 text-[12px] text-muted-foreground/60">
                    Last seen {new Date(device.last_seen_at).toLocaleDateString()}
                  </p>
                )}
              </div>
              <button
                type="button"
                onClick={() => deleteMutation.mutate(device.id)}
                disabled={deleteMutation.isPending}
                className="shrink-0 rounded-md px-3 py-1 text-[12px] font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50"
              >
                Remove
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
