'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  FileText,
  LayoutTemplate,
  ArrowRight,
  Plus,
  Clock,
  GitBranch,
  CheckCircle2,
  Edit3,
  Layers,
  AlertCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { toast } from '@/lib/toast';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getFormDefinitions,
  getPendingSnapshots,
  type FormDefinition,
} from '@/services/api/form-management';
import { ApiClientError } from '@/lib/api-client';

interface QuickStats {
  totalForms: number;
  activeForms: number;
  draftForms: number;
  pendingReview: number;
}

export default function FormsOverviewPage() {
  const router = useRouter();
  const { t, locale } = useTranslation();
  const [stats, setStats] = useState<QuickStats>({
    totalForms: 0,
    activeForms: 0,
    draftForms: 0,
    pendingReview: 0,
  });
  const [loading, setLoading] = useState(true);
  const [recentForms, setRecentForms] = useState<FormDefinition[]>([]);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      // Load data in parallel
      const [allForms, pendingSnapshots] = await Promise.all([
        getFormDefinitions({ limit: 100 }),
        getPendingSnapshots({ limit: 1 }).catch(() => ({ items: [], total: 0 })),
      ]);

      // Statistics
      const activeForms = allForms.items.filter(f => f.status === 'PUBLISHED').length;
      const draftForms = allForms.items.filter(f => f.status === 'DRAFT').length;
      
      setStats({
        totalForms: allForms.total,
        activeForms,
        draftForms,
        pendingReview: pendingSnapshots.total,
      });

      // Recent forms (sorted by update time)
      const recent = [...allForms.items]
        .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
        .slice(0, 5);
      setRecentForms(recent);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.loadFailed}: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const quickActions = [
    {
      title: t.forms.overview.quickActions.createForm,
      description: t.forms.overview.quickActions.createFormDesc,
      icon: Plus,
      href: '/forms/definitions/new',
      bgColor: 'bg-blue-100',
      textColor: 'text-blue-600',
    },
    {
      title: t.forms.overview.quickActions.useTemplate,
      description: t.forms.overview.quickActions.useTemplateDesc,
      icon: LayoutTemplate,
      href: '/forms/templates',
      bgColor: 'bg-green-100',
      textColor: 'text-green-600',
    },
    {
      title: t.forms.overview.quickActions.manageForms,
      description: t.forms.overview.quickActions.manageFormsDesc,
      icon: FileText,
      href: '/forms/definitions',
      bgColor: 'bg-purple-100',
      textColor: 'text-purple-600',
    },
  ];

  const getStatusConfig = (status: FormDefinition['status']) => {
    switch (status) {
      case 'PUBLISHED':
        return { label: t.forms.definition.statusLabels.PUBLISHED, className: 'bg-green-100 text-green-700', icon: CheckCircle2 };
      case 'DRAFT':
        return { label: t.forms.definition.statusLabels.DRAFT, className: 'bg-gray-100 text-gray-700', icon: Edit3 };
      case 'DISABLED':
        return { label: t.forms.definition.statusLabels.DISABLED, className: 'bg-orange-100 text-orange-700', icon: AlertCircle };
      case 'ARCHIVED':
        return { label: t.forms.definition.statusLabels.ARCHIVED, className: 'bg-gray-100 text-gray-500', icon: Clock };
      default:
        return { label: status, className: 'bg-gray-100 text-gray-700', icon: FileText };
    }
  };

  const formatTimeAgo = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (locale === 'zh') {
      if (diffMins < 60) return `${diffMins}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      if (diffDays < 7) return `${diffDays}天前`;
      return date.toLocaleDateString('zh-CN');
    } else {
      if (diffMins < 60) return `${diffMins} min ago`;
      if (diffHours < 24) return `${diffHours}h ago`;
      if (diffDays < 7) return `${diffDays}d ago`;
      return date.toLocaleDateString('en-US');
    }
  };

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      <div className="flex-1 overflow-auto">
        <div className="p-6 space-y-5">
          {/* Statistics Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-white rounded-lg shadow-sm p-3" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.forms.overview.stats.totalForms}
                  </p>
                  <p className="text-xl font-semibold mt-1" style={{ color: '#1f2329' }}>
                    {loading ? '-' : stats.totalForms}
                  </p>
                </div>
                <div 
                  className="w-9 h-9 rounded-lg flex items-center justify-center" 
                  style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}
                >
                  <Layers className="w-4 h-4 text-blue-600" />
                </div>
              </div>
              <div className="mt-2">
                <Button
                  variant="link"
                  className="p-0 h-auto text-xs text-blue-600 hover:text-blue-700"
                  onClick={() => router.push('/forms/definitions')}
                >
                  {t.forms.overview.viewAll} <ArrowRight className="w-3 h-3 ml-1" />
                </Button>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.forms.overview.stats.activeForms}
                  </p>
                  <p className="text-xl font-semibold mt-1" style={{ color: '#1f2329' }}>
                    {loading ? '-' : stats.activeForms}
                  </p>
                </div>
                <div 
                  className="w-9 h-9 rounded-lg flex items-center justify-center" 
                  style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}
                >
                  <CheckCircle2 className="w-4 h-4 text-green-600" />
                </div>
              </div>
              <div className="mt-2">
                <Button
                  variant="link"
                  className="p-0 h-auto text-xs text-blue-600 hover:text-blue-700"
                  onClick={() => router.push('/forms/definitions?status=PUBLISHED')}
                >
                  {t.forms.common.view} <ArrowRight className="w-3 h-3 ml-1" />
                </Button>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.forms.overview.stats.draftForms}
                  </p>
                  <p className="text-xl font-semibold mt-1" style={{ color: '#1f2329' }}>
                    {loading ? '-' : stats.draftForms}
                  </p>
                </div>
                <div 
                  className="w-9 h-9 rounded-lg flex items-center justify-center" 
                  style={{ backgroundColor: 'rgba(255, 125, 0, 0.1)' }}
                >
                  <Edit3 className="w-4 h-4 text-orange-600" />
                </div>
              </div>
              <div className="mt-2 flex items-center text-xs" style={{ color: '#8f959e' }}>
                <Clock className="w-3 h-3 mr-1" />
                <span>{t.forms.overview.pendingDesign}</span>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs" style={{ color: '#8f959e' }}>
                    {t.forms.overview.stats.pendingReview}
                  </p>
                  <p className="text-xl font-semibold mt-1" style={{ color: '#1f2329' }}>
                    {loading ? '-' : stats.pendingReview}
                  </p>
                </div>
                <div 
                  className="w-9 h-9 rounded-lg flex items-center justify-center" 
                  style={{ backgroundColor: 'rgba(139, 92, 246, 0.1)' }}
                >
                  <GitBranch className="w-4 h-4 text-purple-600" />
                </div>
              </div>
              <div className="mt-2">
                <Button
                  variant="link"
                  className="p-0 h-auto text-xs text-blue-600 hover:text-blue-700"
                  onClick={() => router.push('/forms/review')}
                >
                  {t.forms.overview.goToReview} <ArrowRight className="w-3 h-3 ml-1" />
                </Button>
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div>
            <h2 className="text-sm font-semibold mb-3" style={{ color: '#1f2329' }}>
              {t.forms.overview.quickActions.title}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {quickActions.map((action) => {
                const Icon = action.icon;
                return (
                  <button
                    key={action.href}
                    onClick={() => router.push(action.href)}
                    className="bg-white rounded-lg shadow-sm text-left transition-all group p-3"
                    style={{ border: '1px solid #e5e6eb' }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.borderColor = '#d0d4d9';
                      e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.08)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.borderColor = '#e5e6eb';
                      e.currentTarget.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.05)';
                    }}
                  >
                    <div className="flex items-start gap-3">
                      <div 
                        className={`w-8 h-8 ${action.bgColor} rounded-lg flex items-center justify-center flex-shrink-0`}
                      >
                        <Icon className={`w-4 h-4 ${action.textColor}`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 
                          className="font-medium text-sm mb-0.5 transition-colors" 
                          style={{ color: '#1f2329' }}
                        >
                          {action.title}
                        </h3>
                        <p className="text-xs leading-relaxed" style={{ color: '#8f959e' }}>
                          {action.description}
                        </p>
                      </div>
                      <ArrowRight className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5 group-hover:translate-x-1 transition-transform" />
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Recent Forms */}
          <div>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-base font-semibold" style={{ color: '#1f2329' }}>
                {t.forms.overview.recentForms}
              </h2>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => router.push('/forms/definitions')}
                style={{ color: '#646a73' }}
              >
                {t.forms.overview.viewAll}
                <ArrowRight className="w-4 h-4 ml-1" />
              </Button>
            </div>
            <div className="bg-white rounded-lg shadow-sm overflow-hidden" style={{ border: '1px solid #e5e6eb' }}>
              {loading ? (
                <div className="p-8 text-center" style={{ color: '#8f959e' }}>
                  {t.forms.common.loading}
                </div>
              ) : recentForms.length === 0 ? (
                <div className="p-8 text-center">
                  <FileText className="w-12 h-12 mx-auto mb-4" style={{ color: '#c9cdd4' }} />
                  <p style={{ color: '#8f959e' }}>{t.forms.definition.noForms}</p>
                  <Button
                    variant="link"
                    onClick={() => router.push('/forms/definitions/new')}
                    className="mt-2 text-blue-600"
                  >
                    {t.forms.definition.createFirst}
                  </Button>
                </div>
              ) : (
                <table className="w-full">
                  <thead style={{ backgroundColor: '#fafafa' }}>
                    <tr style={{ borderBottom: '1px solid #e5e6eb' }}>
                      <th 
                        className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"
                        style={{ color: '#646a73' }}
                      >
                        {t.forms.overview.formNameColumn}
                      </th>
                      <th 
                        className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"
                        style={{ color: '#646a73' }}
                      >
                        {t.forms.definition.category}
                      </th>
                      <th 
                        className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"
                        style={{ color: '#646a73' }}
                      >
                        {t.forms.overview.lastModifiedColumn}
                      </th>
                      <th 
                        className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"
                        style={{ color: '#646a73' }}
                      >
                        {t.forms.definition.status}
                      </th>
                      <th 
                        className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider"
                        style={{ color: '#646a73' }}
                      >
                        {t.forms.definition.actions}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentForms.map((form, index) => {
                      const statusConfig = getStatusConfig(form.status);
                      const StatusIcon = statusConfig.icon;
                      return (
                        <tr 
                          key={form.id}
                          style={{ 
                            borderBottom: index < recentForms.length - 1 ? '1px solid #e5e6eb' : 'none'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#fafafa';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'transparent';
                          }}
                        >
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center">
                              <FileText className="w-4 h-4 mr-2" style={{ color: '#8f959e' }} />
                              <div>
                                <span className="text-sm font-medium" style={{ color: '#1f2329' }}>
                                  {form.name}
                                </span>
                                <span className="text-xs font-mono ml-2" style={{ color: '#c9cdd4' }}>
                                  {form.key}
                                </span>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span className="text-sm" style={{ color: '#646a73' }}>
                              {form.category || '-'}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span className="text-sm" style={{ color: '#646a73' }}>
                              {formatTimeAgo(form.updatedAt)}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${statusConfig.className}`}>
                              <StatusIcon className="w-3 h-3" />
                              {statusConfig.label}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => router.push(`/forms/definitions/${form.id}/design`)}
                              style={{ color: '#646a73' }}
                            >
                              <Edit3 className="w-4 h-4 mr-1" />
                              {t.forms.definition.designForm}
                            </Button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
