import { useState, useEffect, useCallback } from 'react';

export type FeedbackStatus = 'ok' | 'issue';

export interface Feedback {
  status: FeedbackStatus;
  comment: string;
  tester: string;
  date: string;
}

export interface TestingIssue {
  id: string;
  checkId: string;
  service: string;
  section: string;
  instruction: string;
  comment: string;
  tester: string;
  date: string;
  resolved: boolean;
}

interface StorageData {
  feedbacks: Record<string, Feedback>;
  issues: TestingIssue[];
}

const STORAGE_KEY = 'fitcrm-test-feedback';

function load(): StorageData {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return JSON.parse(raw) as StorageData;
  } catch { /* ignore */ }
  return { feedbacks: {}, issues: [] };
}

function save(data: StorageData) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}

export function useTestFeedback() {
  const [data, setData] = useState<StorageData>({ feedbacks: {}, issues: [] });
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setData(load());
    setMounted(true);
  }, []);

  const persist = useCallback((next: StorageData) => {
    setData(next);
    save(next);
  }, []);

  const setFeedback = useCallback((checkId: string, fb: Feedback) => {
    const next = { ...load() };
    next.feedbacks = { ...next.feedbacks, [checkId]: fb };
    persist(next);
  }, [persist]);

  const addIssue = useCallback((issue: Omit<TestingIssue, 'id' | 'resolved'>) => {
    const next = { ...load() };
    const newIssue: TestingIssue = {
      ...issue,
      id: `issue-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
      resolved: false,
    };
    next.issues = [...next.issues, newIssue];
    persist(next);
    return newIssue;
  }, [persist]);

  const resolveIssue = useCallback((issueId: string) => {
    const next = { ...load() };
    next.issues = next.issues.map((i) =>
      i.id === issueId ? { ...i, resolved: true } : i,
    );
    persist(next);
  }, [persist]);

  const deleteIssue = useCallback((issueId: string) => {
    const next = { ...load() };
    const issue = next.issues.find((i) => i.id === issueId);
    if (issue) {
      delete next.feedbacks[issue.checkId];
    }
    next.issues = next.issues.filter((i) => i.id !== issueId);
    persist(next);
  }, [persist]);

  const clearFeedback = useCallback((checkId: string) => {
    const next = { ...load() };
    delete next.feedbacks[checkId];
    next.issues = next.issues.filter((i) => i.checkId !== checkId);
    persist(next);
  }, [persist]);

  const getStats = useCallback(() => {
    const fbs = Object.values(data.feedbacks);
    return {
      total: fbs.length,
      ok: fbs.filter((f) => f.status === 'ok').length,
      issues: data.issues.filter((i) => !i.resolved).length,
      resolved: data.issues.filter((i) => i.resolved).length,
    };
  }, [data]);

  return {
    feedbacks: mounted ? data.feedbacks : {},
    issues: mounted ? data.issues : [],
    mounted,
    setFeedback,
    addIssue,
    resolveIssue,
    deleteIssue,
    clearFeedback,
    getStats,
  };
}
