"use client";

import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  FileText,
  Upload,
  Calculator,
  CheckCircle,
  Send,
  Clock,
  User,
  AlertTriangle,
  Settings,
  Shield,
} from "lucide-react";
import { formatDate } from "@/lib/formatting";

// Mock audit data - in real app this would come from API
const mockAuditEvents = [
  {
    id: "audit-1",
    type: "document_uploaded",
    title: "Document uploaded",
    description: "P60 Employment Certificate uploaded for John Smith",
    clientId: "client-1",
    clientName: "John Smith",
    userId: "user-1",
    userName: "Sarah Wilson",
    userRole: "preparer",
    timestamp: "2024-01-10T14:30:00Z",
    metadata: {
      fileName: "P60_2023-24.pdf",
      fileSize: "245KB",
      documentType: "P60",
    },
    severity: "info",
  },
  {
    id: "audit-2",
    type: "schedule_computed",
    title: "Schedule computed",
    description: "SA103 Self Employment schedule calculated for Sarah Johnson",
    clientId: "client-2",
    clientName: "Sarah Johnson",
    userId: "user-2",
    userName: "Mike Davis",
    userRole: "reviewer",
    timestamp: "2024-01-10T13:15:00Z",
    metadata: {
      scheduleType: "SA103",
      profit: "£45,000",
      taxLiability: "£8,500",
    },
    severity: "info",
  },
  {
    id: "audit-3",
    type: "coverage_check_failed",
    title: "Coverage check failed",
    description:
      "Missing evidence identified for Michael Brown - 2 critical items required",
    clientId: "client-3",
    clientName: "Michael Brown",
    userId: "system",
    userName: "System",
    userRole: "system",
    timestamp: "2024-01-10T11:45:00Z",
    metadata: {
      missingItems: ["Bank statements", "Property rental agreement"],
      coverageScore: "65%",
    },
    severity: "warning",
  },
  {
    id: "audit-4",
    type: "form_generated",
    title: "Form generated",
    description: "SA100 Main Return PDF created for Emma Davis",
    clientId: "client-4",
    clientName: "Emma Davis",
    userId: "user-3",
    userName: "Alex Thompson",
    userRole: "preparer",
    timestamp: "2024-01-10T10:20:00Z",
    metadata: {
      formType: "SA100",
      pages: 8,
      taxLiability: "£12,450",
    },
    severity: "info",
  },
  {
    id: "audit-5",
    type: "hmrc_submission",
    title: "HMRC submission prepared",
    description: "Tax return submitted to HMRC for David Wilson",
    clientId: "client-5",
    clientName: "David Wilson",
    userId: "user-2",
    userName: "Mike Davis",
    userRole: "reviewer",
    timestamp: "2024-01-10T09:30:00Z",
    metadata: {
      submissionId: "HMRC-2024-001234",
      taxYear: "2023-24",
      status: "submitted",
    },
    severity: "success",
  },
  {
    id: "audit-6",
    type: "user_login",
    title: "User login",
    description: "Sarah Wilson logged into the platform",
    clientId: null,
    clientName: null,
    userId: "user-1",
    userName: "Sarah Wilson",
    userRole: "preparer",
    timestamp: "2024-01-10T08:00:00Z",
    metadata: {
      ipAddress: "192.168.1.100",
      userAgent: "Chrome 120.0.0.0",
      location: "London, UK",
    },
    severity: "info",
  },
  {
    id: "audit-7",
    type: "policy_updated",
    title: "Coverage policy updated",
    description:
      "Self employment evidence requirements updated by administrator",
    clientId: null,
    clientName: null,
    userId: "admin-1",
    userName: "Admin User",
    userRole: "admin",
    timestamp: "2024-01-09T16:45:00Z",
    metadata: {
      policyType: "self_employment",
      changes: ["Added requirement for business bank statements"],
    },
    severity: "warning",
  },
];

const eventIcons = {
  document_uploaded: Upload,
  schedule_computed: Calculator,
  coverage_check_failed: AlertTriangle,
  form_generated: FileText,
  hmrc_submission: Send,
  user_login: User,
  policy_updated: Settings,
  system_error: AlertTriangle,
  default: Clock,
};

const severityColors = {
  info: "bg-blue-100 text-blue-800 border-blue-200",
  success: "bg-green-100 text-green-800 border-green-200",
  warning: "bg-yellow-100 text-yellow-800 border-yellow-200",
  error: "bg-red-100 text-red-800 border-red-200",
};

const roleColors = {
  admin: "bg-red-100 text-red-800",
  reviewer: "bg-blue-100 text-blue-800",
  preparer: "bg-green-100 text-green-800",
  system: "bg-gray-100 text-gray-800",
};

export function AuditTimeline(): JSX.Element {
  return (
    <div className="space-y-4">
      {mockAuditEvents.map((event, index) => {
        const Icon =
          eventIcons[event.type as keyof typeof eventIcons] ||
          eventIcons.default;
        const isLast = index === mockAuditEvents.length - 1;

        return (
          <div key={event.id} className="relative">
            {/* Timeline line */}
            {!isLast && (
              <div className="absolute left-6 top-12 w-0.5 h-full bg-border" />
            )}

            <Card className="ml-0">
              <CardContent className="p-6">
                <div className="flex items-start space-x-4">
                  {/* Icon */}
                  <div className="flex-shrink-0">
                    <div className="h-12 w-12 rounded-full bg-background border-2 border-border flex items-center justify-center">
                      <Icon className="h-5 w-5 text-muted-foreground" />
                    </div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between mb-2">
                      <div className="space-y-1">
                        <h3 className="text-lg font-semibold">{event.title}</h3>
                        <p className="text-muted-foreground">
                          {event.description}
                        </p>
                      </div>

                      <div className="flex items-center space-x-2">
                        <Badge
                          variant="outline"
                          className={
                            severityColors[
                              event.severity as keyof typeof severityColors
                            ]
                          }
                        >
                          {event.severity}
                        </Badge>
                        <span className="text-sm text-muted-foreground">
                          {formatDate(event.timestamp, { relative: true })}
                        </span>
                      </div>
                    </div>

                    {/* User and client info */}
                    <div className="flex items-center space-x-4 mb-3">
                      <div className="flex items-center space-x-2">
                        <Avatar className="h-6 w-6">
                          <AvatarFallback className="text-xs">
                            {event.userName === "System" ? (
                              <Shield className="h-3 w-3" />
                            ) : (
                              event.userName
                                .split(" ")
                                .map((n) => n[0])
                                .join("")
                            )}
                          </AvatarFallback>
                        </Avatar>
                        <span className="text-sm font-medium">
                          {event.userName}
                        </span>
                        <Badge
                          variant="outline"
                          className={`text-xs ${
                            roleColors[
                              event.userRole as keyof typeof roleColors
                            ]
                          }`}
                        >
                          {event.userRole}
                        </Badge>
                      </div>

                      {event.clientName && (
                        <>
                          <span className="text-muted-foreground">•</span>
                          <Link
                            href={`/clients/${event.clientId}`}
                            className="text-sm text-primary hover:underline"
                          >
                            {event.clientName}
                          </Link>
                        </>
                      )}
                    </div>

                    {/* Metadata */}
                    {event.metadata &&
                      Object.keys(event.metadata).length > 0 && (
                        <div className="bg-muted/50 rounded-lg p-3">
                          <h4 className="text-sm font-medium mb-2">Details</h4>
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
                            {Object.entries(event.metadata).map(
                              ([key, value]) => (
                                <div key={key} className="flex justify-between">
                                  <span className="text-muted-foreground capitalize">
                                    {key
                                      .replace(/([A-Z])/g, " $1")
                                      .toLowerCase()}
                                    :
                                  </span>
                                  <span className="font-medium">
                                    {Array.isArray(value)
                                      ? value.join(", ")
                                      : String(value)}
                                  </span>
                                </div>
                              )
                            )}
                          </div>
                        </div>
                      )}
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        );
      })}

      {mockAuditEvents.length === 0 && (
        <Card>
          <CardContent className="p-12 text-center">
            <Clock className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
            <div className="text-muted-foreground">
              <div className="text-lg font-medium mb-2">
                No audit events found
              </div>
              <p className="text-sm">
                Activity will appear here as work is completed
              </p>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
