'use client';

import {
  Building2,
  Calendar,
  Download,
  Factory,
  FileText,
  Globe,
  MapPin,
  Ruler,
  Users,
  Zap,
} from 'lucide-react';
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { type IndustrialParkDetail,
  PARK_STATUS_COLORS,
  PARK_STATUS_LABELS,
  REGION_LABELS } from '@/lib/khu-cong-nghiep-api';
import { cn } from '@/lib/utils';

type Tab = 'infrastructure' | 'connectivity' | 'incentives' | 'tenants' | 'documents';

const TABS: { key: Tab; label: string }[] = [
  { key: 'infrastructure', label: 'Hạ tầng' },
  { key: 'connectivity', label: 'Kết nối giao thông' },
  { key: 'incentives', label: 'Ưu đãi đầu tư' },
  { key: 'tenants', label: 'Doanh nghiệp' },
  { key: 'documents', label: 'Tài liệu' },
];

interface KhuCongNghiepDetailClientProps {
  park: IndustrialParkDetail;
}

export function KhuCongNghiepDetailClient({ park }: KhuCongNghiepDetailClientProps) {
  const [activeTab, setActiveTab] = React.useState<Tab>('infrastructure');

  const occupancyColor =
    park.occupancyRate >= 90 ? 'text-red-600' :
    park.occupancyRate >= 70 ? 'text-amber-600' :
    'text-green-600';

  return (
    <div className="mx-auto max-w-7xl px-4 py-6">
      {/* Header */}
      <div className="mb-6">
        <div className="mb-2 flex flex-wrap items-center gap-2">
          <Badge className={cn('text-xs', PARK_STATUS_COLORS[park.status])} variant="secondary">
            {PARK_STATUS_LABELS[park.status]}
          </Badge>
          <Badge variant="outline" className="text-xs">
            {REGION_LABELS[park.region]}
          </Badge>
          {park.isVerified && (
            <Badge className="bg-blue-100 text-blue-800 text-xs" variant="secondary">
              Đã xác minh
            </Badge>
          )}
        </div>
        <h1 className="text-2xl font-bold md:text-3xl">{park.name}</h1>
        {park.nameEn && (
          <p className="mt-1 text-lg text-muted-foreground">{park.nameEn}</p>
        )}
        <div className="mt-2 flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
          <span className="flex items-center gap-1">
            <MapPin className="h-4 w-4" />
            {park.address}, {park.district}, {park.province}
          </span>
          <span className="flex items-center gap-1">
            <Building2 className="h-4 w-4" />
            {park.developer}
          </span>
          {park.establishedYear && (
            <span className="flex items-center gap-1">
              <Calendar className="h-4 w-4" />
              Thành lập: {park.establishedYear}
            </span>
          )}
        </div>
      </div>

      {/* Quick stats */}
      <div className="my-6 grid grid-cols-2 gap-4 rounded-lg border bg-card p-4 sm:grid-cols-4 lg:grid-cols-6">
        <QuickStat
          icon={<Ruler className="h-5 w-5" />}
          label="Tổng diện tích"
          value={`${park.totalAreaHa.toLocaleString()} ha`}
        />
        <QuickStat
          icon={<Factory className="h-5 w-5" />}
          label="DT cho thuê"
          value={`${park.leasableAreaHa.toLocaleString()} ha`}
        />
        <QuickStat
          label="Tỷ lệ lấp đầy"
          value={`${park.occupancyRate}%`}
          valueClassName={occupancyColor}
        />
        <QuickStat
          label="Còn trống"
          value={`${park.remainingAreaHa.toLocaleString()} ha`}
        />
        <QuickStat
          icon={<Users className="h-5 w-5" />}
          label="Doanh nghiệp"
          value={`${park.tenantCount}`}
        />
        <QuickStat
          label="Tin đăng"
          value={`${park.listingCount}`}
        />
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Main content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Description */}
          {park.description && (
            <Card>
              <CardHeader>
                <CardTitle>Giới thiệu</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="whitespace-pre-wrap text-sm leading-relaxed">
                  {park.description}
                </p>
              </CardContent>
            </Card>
          )}

          {/* Target industries */}
          {park.targetIndustries.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Ngành nghề thu hút</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-2">
                  {park.targetIndustries.map((industry) => (
                    <Badge key={industry} variant="secondary">
                      {industry}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Certifications */}
          {park.certifications && park.certifications.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Chứng nhận</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-2">
                  {park.certifications.map((cert) => (
                    <Badge key={cert} variant="outline" className="gap-1">
                      <Globe className="h-3 w-3" />
                      {cert}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Tabs */}
          <div>
            <div className="flex gap-1 overflow-x-auto border-b" role="tablist">
              {TABS.map((tab) => (
                <button
                  key={tab.key}
                  role="tab"
                  aria-selected={activeTab === tab.key}
                  className={cn(
                    'shrink-0 border-b-2 px-4 py-2 text-sm font-medium transition-colors',
                    activeTab === tab.key
                      ? 'border-primary text-primary'
                      : 'border-transparent text-muted-foreground hover:text-foreground',
                  )}
                  onClick={() => setActiveTab(tab.key)}
                >
                  {tab.label}
                </button>
              ))}
            </div>

            <div className="mt-4">
              {activeTab === 'infrastructure' && <InfrastructureTab park={park} />}
              {activeTab === 'connectivity' && <ConnectivityTab park={park} />}
              {activeTab === 'incentives' && <IncentivesTab park={park} />}
              {activeTab === 'tenants' && <TenantsTab park={park} />}
              {activeTab === 'documents' && <DocumentsTab park={park} />}
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Rent info */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Giá thuê</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {park.landRentUsdM2Year != null ? (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Thuê đất</span>
                  <span className="font-semibold text-primary">
                    ${park.landRentUsdM2Year}/m²/năm
                  </span>
                </div>
              ) : null}
              {park.rbfRentUsdM2Month != null ? (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Nhà xưởng xây sẵn</span>
                  <span className="font-semibold">${park.rbfRentUsdM2Month}/m²/tháng</span>
                </div>
              ) : null}
              {park.rbwRentUsdM2Month != null ? (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Nhà kho</span>
                  <span className="font-semibold">${park.rbwRentUsdM2Month}/m²/tháng</span>
                </div>
              ) : null}
              {park.managementFeeUsd != null ? (
                <div className="flex items-center justify-between border-t pt-3">
                  <span className="text-sm text-muted-foreground">Phí quản lý</span>
                  <span className="font-semibold">${park.managementFeeUsd}/m²/năm</span>
                </div>
              ) : null}
              {park.landRentUsdM2Year == null &&
                park.rbfRentUsdM2Month == null &&
                park.rbwRentUsdM2Month == null && (
                <p className="text-sm text-muted-foreground">Liên hệ để biết giá thuê</p>
              )}
            </CardContent>
          </Card>

          {/* Developer / Operator */}
          <Card className="lg:sticky lg:top-20">
            <CardHeader>
              <CardTitle className="text-base">Thông tin quản lý</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div>
                <p className="text-xs text-muted-foreground">Chủ đầu tư</p>
                <div className="mt-1 flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
                    <Building2 className="h-4 w-4 text-primary" />
                  </div>
                  <p className="text-sm font-medium">{park.developer}</p>
                </div>
              </div>
              {park.operator && (
                <div>
                  <p className="text-xs text-muted-foreground">Đơn vị vận hành</p>
                  <p className="mt-1 text-sm font-medium">{park.operator}</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ─── Sub-components ────────────────────────────────────────

function QuickStat({
  icon,
  label,
  value,
  valueClassName,
}: {
  icon?: React.ReactNode;
  label: string;
  value: string;
  valueClassName?: string;
}) {
  return (
    <div className="flex items-center gap-2">
      {icon && <div className="text-muted-foreground">{icon}</div>}
      <div>
        <p className="text-xs text-muted-foreground">{label}</p>
        <p className={cn('text-sm font-semibold', valueClassName)}>{value}</p>
      </div>
    </div>
  );
}

function InfrastructureTab({ park }: { park: IndustrialParkDetail }) {
  if (!park.infrastructure || Object.keys(park.infrastructure).length === 0) {
    return <p className="text-sm text-muted-foreground">Chưa cập nhật thông tin hạ tầng.</p>;
  }

  return (
    <div className="grid gap-3 sm:grid-cols-2">
      {Object.entries(park.infrastructure).map(([key, value]) => (
        <div key={key} className="rounded-lg border p-3">
          <p className="text-xs font-medium text-muted-foreground capitalize">{key.replace(/_/g, ' ')}</p>
          <p className="mt-1 text-sm">{value}</p>
        </div>
      ))}
    </div>
  );
}

function ConnectivityTab({ park }: { park: IndustrialParkDetail }) {
  if (!park.connectivity || Object.keys(park.connectivity).length === 0) {
    return <p className="text-sm text-muted-foreground">Chưa cập nhật thông tin kết nối giao thông.</p>;
  }

  return (
    <div className="space-y-2">
      {Object.entries(park.connectivity).map(([key, info]) => (
        <div key={key} className="flex items-center justify-between rounded-lg border p-3">
          <div>
            <p className="text-xs font-medium text-muted-foreground capitalize">{key.replace(/_/g, ' ')}</p>
            <p className="text-sm font-medium">{info.name}</p>
          </div>
          <Badge variant="secondary">{info.distanceKm} km</Badge>
        </div>
      ))}
    </div>
  );
}

function IncentivesTab({ park }: { park: IndustrialParkDetail }) {
  if (!park.incentives || Object.keys(park.incentives).length === 0) {
    return <p className="text-sm text-muted-foreground">Chưa cập nhật thông tin ưu đãi.</p>;
  }

  return (
    <div className="space-y-3">
      {Object.entries(park.incentives).map(([key, value]) => (
        <div key={key} className="rounded-lg border p-3">
          <div className="flex items-center gap-2">
            <Zap className="h-4 w-4 text-amber-500" />
            <p className="text-sm font-medium capitalize">{key.replace(/_/g, ' ')}</p>
          </div>
          <p className="mt-1 text-sm text-muted-foreground">
            {typeof value === 'string' ? value : JSON.stringify(value)}
          </p>
        </div>
      ))}
    </div>
  );
}

function TenantsTab({ park }: { park: IndustrialParkDetail }) {
  if (!park.existingTenants || park.existingTenants.length === 0) {
    return <p className="text-sm text-muted-foreground">Chưa cập nhật danh sách doanh nghiệp.</p>;
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b">
            <th className="px-3 py-2 text-left font-medium">Doanh nghiệp</th>
            <th className="px-3 py-2 text-left font-medium">Quốc gia</th>
            <th className="px-3 py-2 text-left font-medium">Ngành nghề</th>
          </tr>
        </thead>
        <tbody>
          {park.existingTenants.map((tenant) => (
            <tr key={tenant.name} className="border-b">
              <td className="px-3 py-2 font-medium">{tenant.name}</td>
              <td className="px-3 py-2">{tenant.country}</td>
              <td className="px-3 py-2 text-muted-foreground">{tenant.industry}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function DocumentsTab({ park }: { park: IndustrialParkDetail }) {
  if (!park.documents || park.documents.length === 0) {
    return <p className="text-sm text-muted-foreground">Chưa có tài liệu nào.</p>;
  }

  return (
    <div className="space-y-2">
      {park.documents.map((doc) => (
        <a
          key={doc.url}
          href={doc.url}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-accent"
        >
          <FileText className="h-5 w-5 shrink-0 text-primary" />
          <p className="min-w-0 flex-1 truncate text-sm font-medium">{doc.name}</p>
          <Download className="h-4 w-4 text-muted-foreground" />
        </a>
      ))}
    </div>
  );
}
