import { useState, useEffect, useRef } from 'react';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Badge } from './ui/badge';
import { Skeleton } from './ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import {
  Plus,
  Search,
  Edit,
  Trash2,
  Zap,
  Send,
  AlertCircle,
  Loader2,
  GitBranch,
  X,
} from 'lucide-react';
import { Workflow } from '../types/workflow';
import { workflowService } from '../services/workflows';
import { toast } from '../lib/toast';
import { __, _n, sprintf } from '../lib/i18n';

function formatRelativeTime(dateString: string): string {
  // Parse as UTC if no timezone indicator present (WordPress stores in UTC)
  const normalizedDate =
    dateString.includes('T') || dateString.includes('Z')
      ? dateString
      : dateString.replace(' ', 'T') + 'Z';
  const date = new Date(normalizedDate);
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60) return __('Just now');
  if (diffInSeconds < 3600) {
    const mins = Math.floor(diffInSeconds / 60);
    return sprintf(_n('%d minute ago', '%d minutes ago', mins), mins);
  }
  if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600);
    return sprintf(_n('%d hour ago', '%d hours ago', hours), hours);
  }
  if (diffInSeconds < 604800) {
    const days = Math.floor(diffInSeconds / 86400);
    return sprintf(_n('%d day ago', '%d days ago', days), days);
  }
  if (diffInSeconds < 2592000) {
    const weeks = Math.floor(diffInSeconds / 604800);
    return sprintf(_n('%d week ago', '%d weeks ago', weeks), weeks);
  }
  return date.toLocaleDateString();
}

// localStorage key for persisting filter state
const FILTER_STORAGE_KEY = 'sequensy_workflow_filters';

interface FilterState {
  searchQuery: string;
  statusFilter: string;
  triggerFilter: string;
  sortBy: string;
}

function getPersistedFilters(): Partial<FilterState> {
  try {
    const stored = localStorage.getItem(FILTER_STORAGE_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
  } catch {
    // Ignore parse errors
  }
  return {};
}

interface WorkflowListProps {
  workflows: Workflow[];
  loading: boolean;
  error: string | null;
  onEditWorkflow: (workflowId: string) => void;
  onCreateNew: () => void;
  onRefresh: () => void;
}

export default function WorkflowList({
  workflows,
  loading,
  error,
  onEditWorkflow,
  onCreateNew,
  onRefresh,
}: WorkflowListProps) {
  // Initialize filter state from localStorage
  const persistedFilters = useRef(getPersistedFilters());
  const [searchQuery, setSearchQuery] = useState(persistedFilters.current.searchQuery || '');
  const [statusFilter, setStatusFilter] = useState(persistedFilters.current.statusFilter || 'all');
  const [triggerFilter, setTriggerFilter] = useState(
    persistedFilters.current.triggerFilter || 'all',
  );
  const [sortBy, setSortBy] = useState(persistedFilters.current.sortBy || 'recent');
  const [deleteLoading, setDeleteLoading] = useState<number | null>(null);

  // Persist filter state to localStorage (debounced)
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      const filterState: FilterState = { searchQuery, statusFilter, triggerFilter, sortBy };
      localStorage.setItem(FILTER_STORAGE_KEY, JSON.stringify(filterState));
    }, 300);
    return () => clearTimeout(timeoutId);
  }, [searchQuery, statusFilter, triggerFilter, sortBy]);

  // Derive unique trigger types from workflows
  const availableTriggers = [...new Set(workflows.map((w) => w.trigger_type))].sort();

  const handleDelete = async (id: number, workflowName: string) => {
    if (
      !confirm(__('Are you sure you want to delete this workflow? This action cannot be undone.'))
    ) {
      return;
    }

    setDeleteLoading(id);
    try {
      await workflowService.deleteWorkflow(id);
      toast.success(__('Workflow deleted'), {
        description: sprintf(__('"%s" has been removed.'), workflowName),
      });
      onRefresh();
    } catch (err) {
      toast.error(__('Failed to delete workflow'), {
        description: err instanceof Error ? err.message : __('An error occurred'),
      });
    } finally {
      setDeleteLoading(null);
    }
  };

  // Filter and sort workflows
  const filteredWorkflows = workflows
    .filter((workflow) => {
      const matchesSearch = workflow.name.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesStatus = statusFilter === 'all' || workflow.status === statusFilter;
      const matchesTrigger = triggerFilter === 'all' || workflow.trigger_type === triggerFilter;
      return matchesSearch && matchesStatus && matchesTrigger;
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'executions':
          // TODO: Sort by actual execution count once available from API
          return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
        case 'recent':
        default:
          return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
      }
    });

  // Check if any filters are active
  const hasActiveFilters = searchQuery || statusFilter !== 'all' || triggerFilter !== 'all';

  // Clear all filters
  const clearAllFilters = () => {
    setSearchQuery('');
    setStatusFilter('all');
    setTriggerFilter('all');
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="seq-page-title">{__('Workflows')}</h1>
          <p className="seq-body mt-1">
            {sprintf(
              __('%d of %d workflows active'),
              workflows.filter((w) => w.status === 'active').length,
              workflows.length,
            )}
          </p>
        </div>
        <Button
          variant="accent"
          onClick={onCreateNew}
        >
          <Plus className="w-4 h-4 mr-2" />
          {__('Create Workflow')}
        </Button>
      </div>

      {/* Error Message */}
      {error && (
        <div className="bg-error-muted border border-error rounded-lg p-4 flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-error flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <h3 className="font-semibold text-sm text-slate-900 mb-1">
              {__('Error Loading Workflows')}
            </h3>
            <p className="text-sm text-slate-500 mb-2">{error}</p>
            <Button size="sm" variant="outline" onClick={onRefresh}>
              {__('Retry')}
            </Button>
          </div>
        </div>
      )}

      {/* Filters */}
      <Card>
        <CardContent className="p-4 space-y-3">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder={__('Search workflows...')}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-36">
                <SelectValue placeholder={__('Status')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{__('All Status')}</SelectItem>
                <SelectItem value="active">{__('Active')}</SelectItem>
                <SelectItem value="inactive">{__('Inactive')}</SelectItem>
              </SelectContent>
            </Select>
            {availableTriggers.length > 0 && (
              <Select value={triggerFilter} onValueChange={setTriggerFilter}>
                <SelectTrigger className="w-full sm:w-44">
                  <SelectValue placeholder={__('Trigger')} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{__('All Triggers')}</SelectItem>
                  {availableTriggers.map((trigger) => (
                    <SelectItem key={trigger} value={trigger}>
                      {trigger.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
            <div className="hidden sm:block w-px bg-slate-200" />
            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="w-full sm:w-36">
                <SelectValue placeholder={__('Sort by')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="recent">{__('Most Recent')}</SelectItem>
                <SelectItem value="name">{__('Name')}</SelectItem>
                <SelectItem value="executions">{__('Most Used')}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Active Filter Pills */}
          {hasActiveFilters && (
            <div className="flex flex-wrap items-center gap-2">
              <span className="text-sm text-slate-500">{__('Filters:')}</span>
              {searchQuery && (
                <Badge variant="secondary" className="gap-1 pr-1">
                  {sprintf(
                    __('Search: "%s"'),
                    searchQuery.length > 15 ? searchQuery.slice(0, 15) + '...' : searchQuery,
                  )}
                  <button
                    onClick={() => setSearchQuery('')}
                    className="ml-1 hover:bg-slate-300 rounded p-0.5"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </Badge>
              )}
              {statusFilter !== 'all' && (
                <Badge variant="secondary" className="gap-1 pr-1">
                  {sprintf(
                    __('Status: %s'),
                    statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1),
                  )}
                  <button
                    onClick={() => setStatusFilter('all')}
                    className="ml-1 hover:bg-slate-300 rounded p-0.5"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </Badge>
              )}
              {triggerFilter !== 'all' && (
                <Badge variant="secondary" className="gap-1 pr-1">
                  {sprintf(
                    __('Trigger: %s'),
                    triggerFilter.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()),
                  )}
                  <button
                    onClick={() => setTriggerFilter('all')}
                    className="ml-1 hover:bg-slate-300 rounded p-0.5"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </Badge>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={clearAllFilters}
                className="text-slate-500 hover:text-slate-700 h-6 px-2"
              >
                {__('Clear all')}
              </Button>
            </div>
          )}

          {/* Result count when filtered */}
          {hasActiveFilters && workflows.length > 0 && (
            <p className="text-sm text-slate-500">
              {sprintf(
                __('Showing %d of %d workflows'),
                filteredWorkflows.length,
                workflows.length,
              )}
            </p>
          )}
        </CardContent>
      </Card>

      {/* Loading State - Skeleton */}
      {loading && (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{__('Workflow')}</TableHead>
                <TableHead>{__('Trigger')}</TableHead>
                <TableHead>{__('Actions')}</TableHead>
                <TableHead>{__('Status')}</TableHead>
                <TableHead>{__('Updated')}</TableHead>
                <TableHead className="text-right">{__('Actions')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {[1, 2, 3].map((i) => (
                <TableRow key={i}>
                  <TableCell>
                    <Skeleton className="h-5 w-32 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-24 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-20 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-5 w-16 rounded-full skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-20 skeleton-shimmer" />
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Skeleton className="h-8 w-8 skeleton-shimmer" />
                      <Skeleton className="h-8 w-8 skeleton-shimmer" />
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Empty State - No workflows exist */}
      {!loading && !error && workflows.length === 0 && (
        <Card className="animate-fade-in">
          <CardContent className="p-12 flex flex-col items-center text-center">
            <div className="w-16 h-16 rounded-full bg-cyan-100 flex items-center justify-center mb-4">
              <GitBranch className="h-8 w-8 text-cyan-600" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">{__('No workflows yet')}</h3>
            <p className="text-sm text-slate-500 mb-6 max-w-sm">
              {__(
                'Workflows automate actions when events happen. Create your first one to get started.',
              )}
            </p>
            <Button
              variant="accent"
              className="btn-press"
              onClick={onCreateNew}
            >
              <Plus className="w-4 h-4 mr-2" />
              {__('Create Your First Workflow')}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Empty State - No matching results after filtering */}
      {!loading && !error && workflows.length > 0 && filteredWorkflows.length === 0 && (
        <Card className="animate-fade-in">
          <CardContent className="p-12 flex flex-col items-center text-center">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <Search className="h-8 w-8 text-slate-400" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">
              {__('No matching workflows')}
            </h3>
            <p className="text-sm text-slate-500 mb-6 max-w-sm">
              {__('No workflows match your current filters. Try adjusting your search or filters.')}
            </p>
            <Button variant="outline" onClick={clearAllFilters}>
              {__('Clear all filters')}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Workflows Table */}
      {!loading && !error && workflows.length > 0 && (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{__('Workflow')}</TableHead>
                <TableHead>{__('Trigger')}</TableHead>
                <TableHead>{__('Actions')}</TableHead>
                <TableHead>{__('Status')}</TableHead>
                <TableHead>{__('Updated')}</TableHead>
                <TableHead className="text-right">{__('Actions')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredWorkflows.map((workflow) => (
                <TableRow key={workflow.id} className="hover:bg-slate-50">
                  <TableCell className="font-medium text-slate-900">
                    {workflow.name}
                    {workflow.description && (
                      <div className="text-xs text-slate-500 mt-1">{workflow.description}</div>
                    )}
                  </TableCell>
                  <TableCell className="text-sm text-slate-500">
                    <div className="flex items-center gap-2">
                      <Zap className="h-3.5 w-3.5 text-trigger" />
                      {workflow.trigger_type}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-slate-500">
                    <div className="flex items-center gap-2">
                      <Send className="h-3.5 w-3.5 text-action" />
                      {sprintf(
                        _n('%d action', '%d actions', Object.keys(workflow.draft_config?.actions ?? {}).length || 0),
                        Object.keys(workflow.draft_config?.actions ?? {}).length || 0,
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    {workflow.status === 'active' && (
                      <Badge variant="success">{__('Active')}</Badge>
                    )}
                    {workflow.status === 'inactive' && (
                      <Badge variant="secondary">{__('Inactive')}</Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-sm text-slate-500">
                    {formatRelativeTime(workflow.updated_at)}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onEditWorkflow(workflow.id.toString())}
                      >
                        <Edit className="h-4 w-4 text-slate-500" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDelete(workflow.id, workflow.name)}
                        disabled={deleteLoading === workflow.id}
                      >
                        {deleteLoading === workflow.id ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="h-4 w-4 text-error" />
                        )}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}
    </div>
  );
}
