"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import type { EmployeeWithRelations } from "@/features/employees/types"

// ─── Tabs ─────────────────────────────────────────────────────────────────────
const TABS = ["General", "Documents", "Salary", "Payroll History"] as const
type Tab = (typeof TABS)[number]

// ─── Helpers ──────────────────────────────────────────────────────────────────
function fmt(date?: Date | string | null) {
  if (!date) return null
  return new Date(date).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  })
}

function currency(amount: number) {
  return new Intl.NumberFormat("en-KW", {
    minimumFractionDigits: 3,
    maximumFractionDigits: 3,
  }).format(amount)
}

// ─── Section wrapper ──────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div>
      <h3 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground mb-3">
        {title}
      </h3>
      <div className="rounded-lg border border-border divide-y divide-border">
        {children}
      </div>
    </div>
  )
}

// ─── Detail row ───────────────────────────────────────────────────────────────
function Row({ label, value, highlight }: { label: string; value?: string | null; highlight?: "green" | "red" }) {
  const valueClass = highlight === "green"
    ? "text-emerald-600 font-semibold"
    : highlight === "red"
      ? "text-red-500 font-semibold"
      : "text-foreground font-medium"

  return (
    <div className="flex items-center justify-between px-4 py-3">
      <span className="text-sm text-muted-foreground w-44 shrink-0">{label}</span>
      <span className={`text-sm text-right flex-1 ${valueClass}`}>
        {value || <span className="text-muted-foreground/40">—</span>}
      </span>
    </div>
  )
}

// ─── Badge ────────────────────────────────────────────────────────────────────
function StatusBadge({ status }: { status: string }) {
  const styles: Record<string, string> = {
    DRAFT: "bg-amber-50 text-amber-700 border-amber-200",
    APPROVED: "bg-blue-50 text-blue-700 border-blue-200",
    PAID: "bg-emerald-50 text-emerald-700 border-emerald-200",
  }
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${styles[status] ?? "bg-muted text-muted-foreground border-border"}`}>
      {status}
    </span>
  )
}

// ─── General tab ─────────────────────────────────────────────────────────────
function GeneralTab({ employee }: { employee: EmployeeWithRelations }) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <Section title="Personal">
        <Row label="Full Name" value={employee.fullName} />
        <Row label="Date of Birth" value={fmt(employee.dob)} />
        <Row label="Nationality" value={employee.nationality} />
        <Row label="Civil ID" value={employee.civilId} />
        <Row label="Phone" value={employee.phone} />
        <Row label="Email" value={employee.email} />
        <Row label="Address" value={employee.address} />
      </Section>

      <Section title="Employment">
        <Row label="Position" value={employee.position} />
        <Row label="Joining Date" value={fmt(employee.joiningDate)} />
        <Row label="Department" value={(employee as any).department?.name} />
        <Row label="Sub-Department" value={(employee as any).subDepartment?.name} />
        <Row label="Branch" value={(employee as any).branch?.name} />
        <Row label="Reporting Manager" value={(employee as any).reportingManager?.fullName} />
        <Row label="BioTime ID" value={(employee as any).zktecoId} />
        {employee.description && (
          <Row label="Description" value={employee.description} />
        )}
      </Section>

      {employee.shifts && employee.shifts.length > 0 && (
        <Section title="Shift">
          {employee.shifts.map((es: any) => (
            <div key={es.id}>
              <Row label="Shift Name" value={es.shift?.name} />
              {es.effectiveFrom && <Row label="Effective From" value={fmt(es.effectiveFrom)} />}
            </div>
          ))}
        </Section>
      )}

      {employee.leaveAllowances && employee.leaveAllowances.length > 0 && (
        <Section title="Leave Allowances">
          {employee.leaveAllowances.map((la: any) => (
            <Row key={la.id} label={la.leaveType?.name ?? "Leave"} value={`${la.days} days`} />
          ))}
        </Section>
      )}
    </div>
  )
}

// ─── File viewer helper ───────────────────────────────────────────────────────
function FileLink({ url, name }: { url?: string | null; name?: string | null }) {
  const [preview, setPreview] = useState(false)

  if (!url) return <span className="text-muted-foreground/40 text-xs">No file</span>

  const isImage = url.startsWith("data:image")

  return (
    <>
      <div className="flex items-center gap-2">
        {/* Preview / open button */}
        <button
          type="button"
          onClick={() => isImage ? setPreview(true) : window.open(url)}
          className="inline-flex items-center gap-1.5 text-xs text-primary underline-offset-2 hover:underline"
        >
          {isImage ? (
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          ) : (
            <svg className="w-3.5 h-3.5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
            </svg>
          )}
          {name ?? "View file"}
        </button>

        {/* Download button */}
        <a
          href={url}
          download={name ?? "document"}
          className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
          title="Download"
        >
          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
              d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
          </svg>
        </a>
      </div>

      {/* Image preview modal */}
      {isImage && preview && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4"
          onClick={() => setPreview(false)}
        >
          <div
            className="relative max-w-3xl w-full bg-background rounded-xl shadow-2xl overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-border">
              <p className="text-sm font-medium truncate">{name ?? "Preview"}</p>
              <div className="flex items-center gap-2">
                <a
                  href={url}
                  download={name ?? "document"}
                  className="inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
                >
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                  </svg>
                  Download
                </a>
                <button
                  type="button"
                  onClick={() => setPreview(false)}
                  className="p-1 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>
            {/* Image */}
            <div className="p-4 flex items-center justify-center bg-muted/20 min-h-48">
              <img
                src={url}
                alt={name ?? "document"}
                className="max-h-[70vh] max-w-full object-contain rounded"
              />
            </div>
          </div>
        </div>
      )}
    </>
  )
}

// ─── Documents tab ────────────────────────────────────────────────────────────
function DocumentsTab({ employee }: { employee: EmployeeWithRelations }) {
  const doc = (employee as any).document

  function expiryStatus(date?: Date | string | null): { label: string; color: string } | null {
    if (!date) return null
    const d = new Date(date)
    const now = new Date()
    const diffDays = Math.ceil((d.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
    if (diffDays < 0) return { label: "Expired", color: "text-red-600 font-semibold" }
    if (diffDays <= 30) return { label: `Expires in ${diffDays}d`, color: "text-amber-600 font-semibold" }
    if (diffDays <= 90) return { label: `Expires in ${diffDays}d`, color: "text-yellow-600" }
    return { label: "Valid", color: "text-emerald-600" }
  }

  function DocRow({
    label,
    number,
    expiry,
    fileUrl,
    fileName,
  }: {
    label: string
    number?: string | null
    expiry?: Date | string | null
    fileUrl?: string | null
    fileName?: string | null
  }) {
    const status = expiryStatus(expiry)
    return (
      <div className="px-4 py-4 space-y-2">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1">
          <span className="text-sm text-muted-foreground w-44 shrink-0">{label}</span>
          <div className="flex flex-1 items-center justify-between gap-4">
            <span className="text-sm font-medium text-foreground">
              {number || <span className="text-muted-foreground/40">—</span>}
            </span>
            <div className="text-right text-xs space-y-0.5">
              {fmt(expiry) ? (
                <>
                  <p className="text-muted-foreground">{fmt(expiry)}</p>
                  {status && <p className={status.color}>{status.label}</p>}
                </>
              ) : (
                <p className="text-muted-foreground/40">No expiry</p>
              )}
            </div>
          </div>
        </div>
        {/* File row */}
        <div className="flex items-center gap-2 pl-0 sm:pl-44">
          <FileLink url={fileUrl} name={fileName} />
        </div>
      </div>
    )
  }

  const hasAnyData = doc || employee.civilId

  if (!hasAnyData) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
        <svg className="w-10 h-10 mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <p className="text-sm">No documents on file</p>
      </div>
    )
  }

  return (
    <div className="max-w-2xl space-y-6">
      <div>
        <div className="flex items-center justify-between mb-1">
          <h3 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
            ID Documents
          </h3>
          <span className="text-xs text-muted-foreground">Number · Expiry · File</span>
        </div>
        <div className="rounded-lg border border-border divide-y divide-border">
          <DocRow
            label="Civil ID"
            number={employee.civilId}
            expiry={doc?.civilIdExpiry}
            fileUrl={doc?.civilIdFileUrl}
            fileName={doc?.civilIdFileName}
          />
          <DocRow
            label="Passport"
            number={doc?.passportNumber}
            expiry={doc?.passportExpiry}
            fileUrl={doc?.passportFileUrl}
            fileName={doc?.passportFileName}
          />
          {doc?.otherFileUrl && (
            <div className="px-4 py-4 space-y-1.5">
              <span className="text-sm text-muted-foreground">Other Document</span>
              <div className="pl-0">
                <FileLink url={doc.otherFileUrl} name={doc.otherFileName} />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

// ─── Salary tab ───────────────────────────────────────────────────────────────
function SalaryTab({ employee }: { employee: EmployeeWithRelations }) {
  const components = employee.salaryComponents ?? []

  const deductions = components.filter((c: any) =>
    ["deduction", "tax", "penalty", "absence"].some((k) => c.category.toLowerCase().includes(k))
  )
  const additions = components.filter((c: any) => !deductions.includes(c))
  const allComponents = [...additions, ...deductions]

  const totalAdditions = additions.reduce((s: number, c: any) => s + c.amount, 0)
  const totalDeductions = deductions.reduce((s: number, c: any) => s + c.amount, 0)
  const net = totalAdditions - totalDeductions

  if (components.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
        <svg className="w-10 h-10 mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
            d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <p className="text-sm">No salary components configured</p>
        <Button asChild variant="outline" size="sm" className="mt-4">
          <a href={`/employees/edit/${employee.id}`}>Add Components</a>
        </Button>
      </div>
    )
  }

  return (
    <div className="max-w-xl space-y-4">
      <Section title="Components">
        {allComponents.map((c: any) => {
          const isDeduction = deductions.includes(c)
          return (
            <div key={c.id} className="flex items-center justify-between px-4 py-3">
              <div className="flex items-center gap-2.5">
                <span className={`w-2 h-2 rounded-full ${isDeduction ? "bg-red-400" : "bg-emerald-400"}`} />
                <span className="text-sm text-foreground capitalize">{c.category}</span>
              </div>
              <span className={`text-sm font-semibold tabular-nums ${isDeduction ? "text-red-500" : "text-foreground"}`}>
                {isDeduction ? "−" : "+"} {currency(c.amount)}
              </span>
            </div>
          )
        })}
      </Section>

      {/* Summary */}
      <div className="rounded-lg border border-border divide-y divide-border">
        <div className="flex justify-between px-4 py-3">
          <span className="text-sm text-muted-foreground">Total Additions</span>
          <span className="text-sm font-semibold text-emerald-600 tabular-nums">+ {currency(totalAdditions)}</span>
        </div>
        <div className="flex justify-between px-4 py-3">
          <span className="text-sm text-muted-foreground">Total Deductions</span>
          <span className="text-sm font-semibold text-red-500 tabular-nums">− {currency(totalDeductions)}</span>
        </div>
        <div className="flex justify-between px-4 py-3.5 bg-muted/30 rounded-b-lg">
          <span className="text-sm font-bold">Net Payable</span>
          <span className="text-sm font-bold tabular-nums">{currency(net)}</span>
        </div>
      </div>
    </div>
  )
}

// ─── Payroll History tab ──────────────────────────────────────────────────────
function PayrollHistoryTab({ employee }: { employee: EmployeeWithRelations }) {
  const payrolls: any[] = (employee as any).payrolls ?? []

  const monthName = (m: number) =>
    new Date(2000, m - 1).toLocaleString("en-US", { month: "long" })

  if (payrolls.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
        <svg className="w-10 h-10 mb-3 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <p className="text-sm">No payroll records found</p>
      </div>
    )
  }

  return (
    <div className="rounded-lg border border-border overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="bg-muted/40 border-b border-border">
            {["Period", "Days", "Basic", "Additions", "Deductions", "Net Payable", "Status"].map((h, i) => (
              <th
                key={h}
                className={`px-4 py-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground ${i === 0 ? "text-left" : i === 6 ? "text-center" : "text-right"
                  }`}
              >
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-border">
          {[...payrolls]
            .sort((a: any, b: any) => b.year - a.year || b.month - a.month)
            .map((p: any) => (
              <tr key={p.id} className="hover:bg-muted/20 transition-colors">
                <td className="px-4 py-3 font-semibold text-foreground">
                  {monthName(p.month)} {p.year}
                </td>
                <td className="px-4 py-3 text-right text-muted-foreground tabular-nums">
                  {p.daysWorked}/{p.workingDays}
                </td>
                <td className="px-4 py-3 text-right tabular-nums">{currency(p.basicSalary)}</td>
                <td className="px-4 py-3 text-right tabular-nums text-emerald-600 font-medium">
                  +{currency(p.totalAdditions)}
                </td>
                <td className="px-4 py-3 text-right tabular-nums text-red-500 font-medium">
                  −{currency(p.totalDeductions)}
                </td>
                <td className="px-4 py-3 text-right font-bold tabular-nums">{currency(p.netPayable)}</td>
                <td className="px-4 py-3 text-center">
                  <StatusBadge status={p.status} />
                </td>
              </tr>
            ))}
        </tbody>
      </table>
    </div>
  )
}

// ─── Main ─────────────────────────────────────────────────────────────────────
export default function EmployeeDetails({ employee }: { employee: EmployeeWithRelations }) {
  const [activeTab, setActiveTab] = useState<Tab>("General")
  const [avatarPreview, setAvatarPreview] = useState(false)

  return (
    <div className="space-y-6">
      {/* Avatar */}
      <div className="flex justify-start">
        <button
          type="button"
          onClick={() => employee.avatarUrl && setAvatarPreview(true)}
          className="group relative h-24 w-24 rounded-full focus:outline-none"
          title="View photo"
        >
          {employee.avatarUrl ? (
            <>
              <img
                src={employee.avatarUrl}
                alt={employee.fullName}
                className="h-24 w-24 rounded-full object-cover border border-border shadow-sm transition-opacity group-hover:opacity-80"
              />
              <span className="absolute inset-0 flex items-center justify-center rounded-full bg-black/0 group-hover:bg-black/30 transition-colors">
                <svg className="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
              </span>
            </>
          ) : (
            <div className="flex h-24 w-24 items-center justify-center rounded-full bg-muted border border-border">
              <svg className="h-12 w-12 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                  d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
          )}
        </button>
      </div>

      {/* Avatar preview modal */}
      {employee.avatarUrl && avatarPreview && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4"
          onClick={() => setAvatarPreview(false)}
        >
          <div
            className="relative max-w-sm w-full bg-background rounded-xl shadow-2xl overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between px-4 py-3 border-b border-border">
              <p className="text-sm font-medium">{employee.fullName}</p>
              <div className="flex items-center gap-2">

                <a
                  href={employee.avatarUrl}
                  download={employee.fullName}
                  className="inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
                >
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                  </svg>
                  Download
                </a>
                <button
                  type="button"
                  onClick={() => setAvatarPreview(false)}
                  className="p-1 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>
            <div className="p-4 flex items-center justify-center bg-muted/20">
              <img
                src={employee.avatarUrl}
                alt={employee.fullName}
                className="max-h-[70vh] max-w-full object-contain rounded-lg"
              />
            </div>
          </div>
        </div>
      )
      }

      {/* Tab bar */}
      <div className="flex border-b border-border">
        {TABS.map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2.5 text-sm font-medium transition-colors relative whitespace-nowrap ${activeTab === tab
              ? "text-foreground"
              : "text-muted-foreground hover:text-foreground"
              }`}
          >
            {tab}
            {activeTab === tab && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-foreground rounded-t-full" />
            )}
          </button>
        ))}
      </div>

      {activeTab === "General" && <GeneralTab employee={employee} />}
      {activeTab === "Documents" && <DocumentsTab employee={employee} />}
      {activeTab === "Salary" && <SalaryTab employee={employee} />}
      {activeTab === "Payroll History" && <PayrollHistoryTab employee={employee} />}
    </div >
  )
}